Nginx

Nginx 將 certbot www 重定向到非 www

  • August 21, 2019

我正在嘗試將 HTTPS www 請求重定向到非 www,但我無法讓它工作。我必須更改哪一行程式碼才能實現重定向?

server {
   root /var/www/mydomain.com/html;
   index index.html index.htm index.nginx-debian.html;

   server_name mydomain.com www.mydomain.com;

   #gZip stuff here...
   #Certbot stuff here...
}

server {
   if ($host = www.mydomain.com) {
       return 301 https://$host$request_uri;
   } # managed by Certbot

   if ($host = mydomain.com) {
       return 301 https://$host$request_uri;
   } # managed by Certbot

   listen 80;
   listen [::]:80;

   server_name mydomain.com www.mydomain.com;
   return 404; # managed by Certbot
}

我建議在下面管理提及。根據 Nginx 文件,這也是他們推薦的處理域級別重定向的方法。

server {

       listen 443; 
       server_name www.example.com;
       return 301 $scheme://example.com$request_uri;
   }

   server {

       listen 443;
       server_name example.com;

        root /var/www/mydomain.com/html;
        index index.html index.htm index.nginx-debian.html;

       # Others Configuration...

   }

如果您願意,還可以再添加一個伺服器塊來將 HTTP 重定向到 https。

server {

       listen 80;
       server_name www.example.com example.com;
       return 301 https://example.com$request_uri;
   }

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