Nginx

nginx 在 404 上提供備用位置

  • September 10, 2013

我正在嘗試按如下方式設置 nginx 配置:當收到如下請求時/tile/SteveCountryVic/1/2/3.png

  1. 嘗試將其傳遞給http://localhost:5005/1/2/3.png
  2. 如果是 404s,則將其傳遞給另一台伺服器/tile/SteveCountryVic/1/2/3.png

這是我的配置,它不太工作:

server {
  listen 80;
  server_name localhost;   error_log  /tmp/nginx.error.log notice;
  access_log   /tmp/nginx.access.log;
  location /tile/SteveCountryVic/ {
       rewrite_log on;        
       #rewrite ^.*/(\d+)/(\d+)/(\d+).*$ /$1/$2/$3.png break;

       proxy_intercept_errors on;
       error_page 404 = @dynamiccycletour;        
       #proxy_set_header Host $http_host;
       #proxy_pass http://127.0.0.1:5005;
       proxy_redirect /tile/SteveCountryVic/ http://localhost:5005/;

  location @dynamiccycletour {
       rewrite_log on;
       #rewrite ^(\d+)/(\d+)/(\d+).*$ /tile/SteveCountryVic/$1/$2/$3.png break;
       proxy_pass http://115.x.x.x:20008;


  }

  location /tile/ {
       proxy_set_header Host $http_host;
       proxy_pass http://127.0.0.1:20008;


       proxy_cache my-cache;
       proxy_cache_valid  200 302  60m;
       proxy_cache_valid  404      1m;
   }
   ...

在此配置中,所有請求似乎都被重定向到代理伺服器,但最終會提供圖像。此外,錯誤日誌包含以下行:

2013/09/10 09:44:11 [error] 564#0: *138 open() "/etc/nginx/html/tile/SteveCountryVic/13/7399/5027.png" failed (2: No such file or directory), client: 118.x.x.x, server: localhost, request: "GET /tile/SteveCountryVic/13/7399/5027.png?updated=15 HTTP/1.1", host: "mydomain.org"

如果不使用proxy_redirect,我使用rewriteand proxy_pass

       rewrite ^.*/(\d+)/(\d+)/(\d+).*$ /$1/$2/$3.png break;
       proxy_pass http://127.0.0.1:5005;

然後現在我實際上在瀏覽器中看到了 404 消息(即,它們沒有被截獲)。

我的問題:

  1. 我究竟做錯了什麼?
  2. 為什麼 nginx 在 /etc/nginx/html/… 中尋找文件?
  3. 有沒有辦法獲得更多的日誌資訊(特別是為了更好地理解 proxy_redirect)?

替代版本,使用rewriteproxy_pass表現完美 - 問題是另一台伺服器返回 200 而不是 404。因此,為了完整起見,這裡是工作配置:

server {
  listen 80;
  server_name localhost;
  error_log  /tmp/nginx.error.log notice;
  access_log   /tmp/nginx.access.log;
  location /tile/SteveCountryVic/ {
       rewrite_log on;
       rewrite ^.*/(\d+)/(\d+)/(\d+.*)$ /$1/$2/$3 break;

       proxy_intercept_errors on;
       error_page 404 = @dynamiccycletour;
       proxy_set_header Host $http_host;
       proxy_pass http://127.0.0.1:5005;
 }

  location @dynamiccycletour {
       rewrite_log on;
       rewrite ^/(\d+)/(\d+)/(\d+.*)$ /tile/SteveCountryVic/$1/$2/$3 break;
       proxy_pass http://115.x.x.x:20008;

  }

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