Nginx

設置正確的請求主機以避免 nginx 中的這種無限循環

  • February 8, 2020

我將此 nginx 伺服器配置為記憶體/反向代理example.comwww.example.com從 mysource.example.com 獲取數據

它在瀏覽器中似乎工作正常,但我注意到Google排名顯著下降,當我用 wget 測試 URL 時,我得到一個無限循環。

# test without www , getting infinite loop
wget --header="Host: example.com" http://[SERVER IP]/file.html


Location: https://www.example.com/file.html [following]
--2020-02-07 21:43:14--  https://www.example.com/file.html
Reusing existing connection to www.example.com:443.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://www.example.com/file.html [following]
20 redirections exceeded.
^^^ RIGHT HERE !!!

# but with www it works OK:
wget --header="Host: www.example.com" http://[SERVER IP]/file.html


HTTP request sent, awaiting response... 200 OK
Length: 1307 (1.3K) [text/plain]
Saving to: ‘file.html’

我想我需要host在從非 www 到 www 的重定向中指定另一個?!

或者這只是一個wget 的事情,因為它通常應該在第一次重定向時切換到 www.example.com,但它使非 www 主機不受 nginx 命令的影響?

# redirect http to https
server {
   listen 80;
   server_name example.com;
   server_name www.example.com;

   proxy_set_header Host      www.example.com
   return 301 https://www.example.com$request_uri;
}


# and redirect non www to www
server {
   listen 443 ssl http2;
   server_name example.com;

   proxy_set_header Host      www.example.com;
   return 301 https://www.example.com$request_uri;
}


# main server, SSL
server {

   listen       443 ssl http2;
   server_name  www.example.com;

   location / {

           proxy_pass       http://mysource.example.com:81;

           proxy_set_header Host      www.example.com;

           proxy_set_header X-Real-IP $remote_addr;
           proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;

           proxy_cache             nginx_ramdisk_cache;
   }



} # end of server

問題出在你使用的方式上wget。通過使用:

wget --header="Host: example.com" http://example.com/file.html

您替換wget將執行的每個請求的Host標頭。所以:

  1. wget 連接到80伺服器的埠並被重定向到https://www.example.com/file.html
  2. wget 連接到443伺服器的埠,但發送Host: example.com標頭而不是Host: www.example.com. 它被重定向到https://www.example.com/file.html
  3. 我們2點回來。

所以,你的配置很好,只是你的測試有問題。您永遠不應覆蓋Host標頭,wget會自動將其設置為 URL 中的域。

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