我正在尝试将nginx配置为rails-5 api后端有一个单独的子目录。 (分隔前端和后端)
原来,我在GET“/ bill”下呼叫后端api。现在我想成为它:GET'/ api / bills'。所以'api'下的所有请求都应该重定向到rails app。
但我不能让它发挥作用。重定向有效,但我在日志中看到了导轨:ActionController::RoutingError (No route matches [GET] "/api/bills")
。当然这条路线不存在。 Rails只知道“/ bill”路由。我可以配置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;
}
答案 0 :(得分:2)
在location @app
区域内尝试添加以下内容:
rewrite ^/api(.*)$ $1 break;
这应该在发送上游URI的剩余部分之前剥离/api
前缀。
有关详细信息,请参阅this document。