我在 CentOS 7 上使用 Nginx 和 Ruby on Rails/Puma。我希望 RoR 跳过某些文件路径,直接由 Nginx 提供服务。我在我的网站的“服务器”块中创建了它
location /assets/lib/ {
alias /home/rails/myproject_production/app/assets/javascripts/lib/;
autoindex off;
}
但是,当我调用类似这样的资产时http://www.mydomein.com/assets/lib/myfile.js
,会出现 404 错误。以下是日志中显示的内容
2018/05/11 15:21:47 [error] 242#0: *1 open() "/home/rails/myproject_production/public/assets/lib/myfile.js" failed (2: No such file or directory), client: 50.240.135.5, server: www.mydomein.com, request: "GET /assets/lib/myfile.js HTTP/1.1", host: "www.mydomein.com"
从日志来看,别名似乎根本没有被调用。我在上面遗漏了什么?我的完整配置如下
upstream myproject {
server unix:///home/rails/myproject_production/shared/sockets/puma.sock;
}
# Listener for Apex Domain
server {
listen 80;
server_name www.mydomein.com;
root /home/rails/myproject_production/public; # I assume your app is located at this location
location / {
proxy_pass http://myproject; # match the name of upstream directive which is defined above
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
if ($request_uri ~* "(\/image\/.*)|(.*\.(ico|gif|jpe?g|png)$)") {
expires 60d;
access_log off;
add_header Pragma public;
add_header Cache-Control "public";
break;
}
}
location /assets/lib/ {
alias /home/rails/myproject_production/app/assets/javascripts/lib/;
autoindex off;
}
location /cable {
proxy_pass http://myproject;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location ~* ^/assets/ {
# Per RFC2616 - 1 year maximum expiry
expires 1y;
add_header Cache-Control public;
# Some browsers still send conditional-GET requests if there's a
# Last-Modified header or an ETag header even if they haven't
# reached the expiry date sent in the Expires header.
add_header Last-Modified "";
add_header ETag "";
break;
}
}
答案1
你有两个location
区块:
location /assets/lib/ {
…
}
location ~* ^/assets/ {
…
}
现在,正如 Nginx 中所述文档,Nginx 首先检查前缀位置,并记住最长匹配。然后检查正则表达式位置,如果找到则使用匹配块。如果没有找到,则使用前缀匹配。
因此,对于您的情况,nginx 首先找到第一个location
块并记住它。但是,正则表达式块也匹配,因此 nginx 选择该块。
为了改变 nginx 选择过程,您需要使用:
location ^~ /assets/lib {
…
}
第一个位置。这也意味着正则表达式块中的指令不适用于这些请求。