Nginx

使用 nginx 重寫規則獲取“重定向過多”錯誤

  • November 9, 2018

我正在嘗試重寫以我的站點為目標的域 url,以便所有域名都重寫為 www.example.com 並具有以下配置:

我的網站塊

 server {      
       listen       80 default_server;
       listen   [::]:80 default_server ipv6only=on;

           server_name _;
           rewrite ^ $scheme://www.example.com$request_uri permanent;

   location / {

           # Allow for large file uploads
             client_max_body_size 0;

               proxy_http_version 1.1;
               proxy_pass http://mysite;
               proxy_buffering    off;

               proxy_set_header   X-Real-IP $remote_addr;
               proxy_set_header   X-Scheme $scheme;
               proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
               proxy_set_header   Host $http_host;
   }
}

tomcat 伺服器塊

server {
       listen        80;

       root /opt/site2/www;
       index index.html index.htm;

       # Redirecto root requests to Share
       rewrite ^/$ /share;

       location / {
           # First attempt to serve request as file, then
           # as directory, then fall back to displaying a 404.
           try_files $uri $uri/ /index.html;
       }

       # redirect server error pages to the static page /50x.html
       error_page 502 503 504 /maintenance.html;
           location = /maintenance.html {
           root   /opt/site2/www;
       }

       location /share {

           # Allow for large file uploads
           client_max_body_size 0;

           # Proxy all the requests to Tomcat
           proxy_http_version 1.1;
           #proxy_buffering off;
           proxy_pass http://backend;
           proxy_set_header Host $http_host;
           proxy_set_header X-Real-IP $remote_addr;
           proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
           proxy_set_header X-Forwarded-Host $http_host;
           proxy_set_header X-Forwarded-Server $host;
       }

}

在伺服器塊中,但我收到“重定向過多”錯誤。

現在任何和所有請求都將到達這個伺服器塊:

server {      
   listen    80 default_server;
   listen    [::]:80 default_server ipv6only=on;

   server_name _; # This doesn't do anything
   rewrite ^ $scheme://www.example.com$request_uri permanent;

   # Rest of file irrelevant
}

因為:沒有伺服器塊有一個有效的server_name(因此永遠不會有主機名匹配),這是 default_server。

使用適當的伺服器名稱

因此,要始終將命中伺服器的請求重定向到給定的主機名,請確保有一個明確的伺服器塊www.example.com

server {      
   listen    80;
   listen    [::]:80 ipv6only=on;

   server_name www.example.com;

   # Everything else from "Tomcat server block" 
   # or the proxy_pass config as appropriate
}

並將具有任何其他主機名的請求重定向到它:

server {      
   listen    80 default_server;
   listen    [::]:80 default_server ipv6only=on;

   return 301 http://www.example.com$request_uri;

   # Nothing else, because it wouldn't do anything
}

在上面的註釋中,return 301它被認為是比無條件重寫規則更好的做法。

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