我在 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;
}
}
你有两个
location
块:现在,如 Nginx文档中所述,Nginx 检查第一个前缀位置,并记住最长匹配。然后它检查正则表达式的位置,如果找到则使用匹配的块。如果没有找到,则使用前缀匹配。
所以,在你的情况下,nginx首先找到第一个
location
块,记住它。但是,正则表达式块也匹配,并且 nginx 选择该块。为了改变 nginx 选择过程,你需要使用:
为您的第一个位置。这也意味着正则表达式块中的指令不适用于这些请求。