Nginx

為什麼我的 Nginx 別名指令不起作用?

  • July 18, 2019

我在 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塊:

location /assets/lib/ {
 …
}
location ~* ^/assets/ {
 …
}

現在,如 Nginx文件中所述,Nginx 檢查第一個前綴位置,並記住最長匹配。然後它檢查正則表達式的位置,如果找到則使用匹配的塊。如果沒有找到,則使用前綴匹配。

所以,在你的情況下,nginx首先找到第一個location塊,記住它。但是,正則表達式塊也匹配,並且 nginx 選擇該塊。

為了改變 nginx 選擇過程,你需要使用:

location ^~ /assets/lib {
 …
}

為您的第一個位置。這也意味著正則表達式塊中的指令不適用於這些請求。

引用自:https://serverfault.com/questions/911831