Nginx 重寫以消除“www”不起作用

Nginx 重寫以消除“www”不起作用

我看過很多SE螺紋並做了各種谷歌搜尋並且不明白為什麼我無法重定向www.mysite.commysite.com我的 nginx 伺服器。

第一個伺服器區塊按照您的預期執行http://mysite.info->重定向。https://mysite.info所以我不確定為什麼第二個伺服器區塊沒有對www.mysite.info->執行相同的操作mysite.info

這是我的 nginx.conf 檔案的相關部分:

server {
    server_name mysite.info;
    rewrite ^ https://$server_name$request_uri? permanent;
}

server {
    server_name www.mysite.info;
    rewrite ^ https://mysite.info$request_uri? permanent;
}

server {
    listen   443;
    ssl    on;
    server_name mysite.info;
    # other directives, handling PHP, etc.
}

對出了什麼問題有什麼想法嗎?

答案1

您正在重定向到$server_name位於www.mysite.info第二個server區塊中的 ,因此所做的只是重定向到 HTTPS,而不是更改主機。

rewrite ^ https://mysite.info$request_uri? permanent;

這將處理主機的變更以及 HTTPS 的變更。

如果您希望重定向與協定無關,更好的方法是:

rewrite ^ $scheme://mysite.info$request_uri? permanent;

在最新版本的 nginx 上,這也有效(並且應該更快一點):

return 301 $scheme://mysite.info$request_uri;

相關內容