2016-04-15 71 views
1

我正在嘗試配置nginx爲rails-5 api後端配置單獨的子目錄。 (分開前端和後端)在nginx for rails的子目錄api-app

原件,我打電話給GET「/票據」下的後端api。現在我想成爲它:GET'/ api/bills'。所以'api'下的所有請求都應該重定向到Rails應用程序。

但我不能讓它工作。重定向的作品,但我看到在日誌軌道上:ActionController::RoutingError (No route matches [GET] "/api/bills")。當然這條路線不存在。 Rails只知道「/票據」路線。我可以配置nginx嗎,重定向對Rails是透明的,它會看到像[GET]「/ bills」這樣的請求?

這裏是我目前的配置:

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; 
} 

回答

1

裏面你location @app塊嘗試添加此:

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

這應該上行發送的URI的剩餘部分之前剛脫光/api前綴。

有關詳細信息,請參閱this document