从nginx的官方文档 documentation, 正确的nginx https 301跳转到带www域名方法的方法如下: HTTP 301跳转到带www域名方法 复制代码 代码如下: server { listen 80; server_name example.org; return 301 http://www.example.org$request_uri; } server { listen 80; server_name www.example.org; ... } HTTPS 301跳转到带www域名方法 复制代码 代码如下: server { listen 80; server_name www.domain.com; // $scheme will get the http protocol // and 301 is best practice for tablet, phone, desktop and seo return 301 $scheme://domain.com$request_uri; }
server { listen 80; server_name domain.com; // here goes the rest of your config file // example location / {
要先用 nginx -v 命令检查你所说使用的nginx的版本. 下面是对于旧版本的nginx301跳转到带www域名方法从www.ksharpdabu.info 跳转到 ksharpdabu.info 复制代码 代码如下:server { server_name www.domain.com; rewrite ^(.*) http://domain.com$1 permanent; } server { server_name domain.com; #The rest of your configuration goes here# }
所以需要两个server段。 从ksharpdabu.info 跳转到 www.ksharpdabu.info 复制代码 代码如下:server { server_name domain.com; rewrite ^(.*) http://www.domain.com$1 permanent; } server { server_name www.domain.com; #The rest of your configuration goes here# }
按上面设置后,用rewrite的方法跳转到指定的域名下,利于SEO 下面是我举例,从www.google.com 跳转到 google.com的部分nginx配置内容: 复制代码 代码如下:server { server_name www.google.com; rewrite ^(.*) http://google.com$1 permanent; } server { listen 80; server_name google.com; index index.php index.html; #### # now pull the site from one directory # root /var/www/www.google.com/web; # done # location = /favicon.ico { log_not_found off; access_log off; } }
网上还有一种不用rewirte的 方法,如下: 复制代码 代码如下:server { #listen 80 is default server_name www.example.com; return 301 $scheme://example.com$request_uri; } server { #listen 80 is default server_name example.com; ## here goes the rest of your conf... }