user1908375
user1908375

Reputation: 1089

subdir in nginx for rails api-app

I am trying to configure the nginx to have a separate subdir for rails-5 api backend. (to separate frontend and backend)

Original, I am calling backend api under GET "/bills". Now I'd like to be it: GET '/api/bills'. so all requests under 'api' should be redirected to rails app.

But I can't make it working. The redirection works, but I see on rails side in logs: ActionController::RoutingError (No route matches [GET] "/api/bills"). Of course this route doesn't exists. Rails only knows about the "/bills" route. Could I configure nginx so, that the redirection would be transparent to Rails, and it would see the request like [GET]"/bills" ?

here is my current config:

upstream app {
    # Path to Unicorn SOCK file, as defined previously
    server unix:/var/sockets/unicorn.myapp.sock fail_timeout=0;
}

server {
  #redirect to https      
  listen 0.0.0.0:80;
  listen [::]:80 ipv6only=on default_server;
  server_name localhost; ## Replace this with something like gitlab.example.com
  server_tokens off; ## Don't show the nginx version number, a security best practice
  return 301 https://$server_name$request_uri;
  access_log  /var/log/nginx/app_access.log;
  error_log   /var/log/nginx/app_error.log;
}


server {

    listen 0.0.0.0:443 ssl;
    listen [::]:443 ipv6only=on ssl default_server;
    server_name localhost; ## Replace this with something like gitlab.example.com

    ssl on;
    ssl_certificate /etc/ssl/nginx/host.crt;
    ssl_certificate_key /etc/ssl/nginx/host.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 5m;

    location  ^~  /api {
        #try_files $uri/index.html $uri $uri/;
        try_files $uri/index.html $uri @app;
        root /app/backend/public;
    }


    location @app {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app;

        error_page 500 502 503 504 /500.html;
    }


    location / {
      # Application Frontend root, as defined previously
      try_files $uri $uri/ =404;
      root /app/frontend/;
    }


    client_max_body_size 4G;
    keepalive_timeout 10;
}

Upvotes: 2

Views: 653

Answers (1)

Richard Smith
Richard Smith

Reputation: 49742

Inside your location @app block try adding this:

rewrite ^/api(.*)$ $1 break;

That should just strip off the /api prefix before sending the remainder of the URI upstream.

See this document for details.

Upvotes: 3

Related Questions