文章作者:姜南(Slyar) 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。
还是以前在Apache上做过的事,实现2种情况的需求
方法很简单,把下面的代码按自己的需要加入/usr/local/nginx/conf/nginx.conf 的server段或location段中即可
虚拟主机用户可以修改比如 /usr/local/nginx/conf/vhost/www.slyar.com.conf
需要小注意的一点是,如果你的网站是在子目录下的,你可能需要增加 "location /子目录/ {}" 段来实现子目录的域名统一定向
1、当用户访问顶级域名 slyar.com/***.html 的时候,自动转向带www的 www.slyar.com/***.html 下
1 2 3 4 5 |
location / { if ($host != 'www.slyar.com' ) { rewrite ^/(.*)$ http://www.slyar.com/$1 permanent; } } |
2、当用户访问带www的 www.slyar.com/***.html 的时候,自动转向不带www的顶级域名 slyar.com/***.html 下
1 2 3 4 5 |
location / { if ($host != 'slyar.com' ) { rewrite ^/(.*)$ http://slyar.com/$1 permanent; } } |
或者 比较通用的办法(推荐)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
server { listen 80; server_name slyar.com; return 301 $scheme://www.slyar.com$request_uri; } server { listen 80; server_name www.slyar.com; index index.html index.htm index.php default.html default.htm default.php; root /home/xxxxx; 其他配置 } |
转载请注明:Slyar Home » Nginx下统一顶级域名和www子域名实现自动转向