Web-Server

如何讓 nginx 從 www 重定向到非 www 域?

  • October 28, 2016

假設我想從 www.example.com 重定向到 example.com,並且我想使用 nginx 來做到這一點。我環顧四周,沒有看到任何好的文件,所以我想我會問並回答我自己的問題。

經過一番探勘和一些失誤,這裡是解決方案。我遇到的問題是確保使用“ http://example.com $ uri". Inserting a / in front of $ uri 導致重定向到http://example.com//

 server {
   listen 80;
   server_name www.example.com;
   rewrite ^ http://example.com$uri permanent;
 }

 # the server directive is nginx's virtual host directive.
 server {
   # port to listen on. Can also be set to an IP:PORT
   listen 80;

   # Set the charset
   charset utf-8;

   # Set the max size for file uploads to 10Mb
   client_max_body_size 10M;

   # sets the domain[s] that this vhost server requests for
   server_name example.com;

   # doc root
   root /var/www/example.com;

   # vhost specific access log
   access_log  /var/log/nginx_access.log  main;


   # set vary to off to avoid duplicate headers
   gzip off;
   gzip_vary off;


   # Set image format types to expire in a very long time
   location ~* ^.+\.(jpg|jpeg|gif|png|ico)$ {
       access_log off;
       expires max;
   }

   # Set css and js to expire in a very long time
   location ~* ^.+\.(css|js)$ {
       access_log off;
       expires max;
   }

   # Catchall for everything else
   location / {
     root /var/www/example.com;
     access_log off;

     index index.html;
     expires 1d;

     if (-f $request_filename) {
       break;
     }
   }
 }

我還在 Nginx wiki 和其他部落格上查看了這一點,性能方面的最佳方法是執行以下操作:

使用 nginx(撰寫本文時版本 1.0.12)從 www.example.com 重定向到 example.com。

server {
 server_name www.example.com;
 rewrite ^ $scheme://example.com$request_uri permanent; 
 # permanent sends a 301 redirect whereas redirect sends a 302 temporary redirect
 # $scheme uses http or https accordingly
}

server {
 server_name example.com;
 # the rest of your config goes here
}

當請求來到 example.com 時,不使用 if 語句來提高性能。它使用 $ request_uri rather than having to create a $ 1 匹配對重寫徵稅(請參閱 Nginx 常見陷阱頁面)。

資料來源:

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