NGINX设置域名301重定向的两种方法以及目录重定向

进行了301重定向,把www.sulao.cn和sulao.cn合并,并把之前的域名也一并合并.

有两种实现方法,第一种方法是判断nginx核心变量host(老版本是http_host):

第一种方法:

server {
      server_name www.sulao.cn sulao.cn;
      if ($host != 'www.sulao.cn' ) {
         rewrite ^/(.*)$ https://sulao.cn/$1 permanent;
      }
      ...
}

第二种方法:

server {
if ($host = 'sulao.cn'){
        rewrite ^/(.*)$ https://sulao.cn/$1 permanent;
    }
}

这两种方法中, permanent是关键,详细说明见nginx重定向规则说明。

last – 基本上都用这个Flag。
break – 中止Rewirte,不在继续匹配
redirect – 返回临时重定向的HTTP状态302
permanent – 返回永久重定向的HTTP状态301

好了,现在可以检查结果,在站长工具里可以看返回的HTTP头信息:

测试是否定向成功

/usr/local/nginx/sbin/nginx -t

提示:

the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
configuration file /usr/local/nginx/conf/nginx.conf test is successful

测试成功, 重启nginx,输入命令:

/usr/local/nginx/sbin/nginx -s reload

重启之后测试一下~是否成功设定完成! 输入命令:

curl  –I   sulao.cn

会输出:

HTTP/1.1 301 Moved Permanently
Server: nginx/0.7.65
Date: Tue, 03 Aug 2010 01:12:37 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: https://sulao.cn/

目录重定向

if ( $request_filename ~ html/ ) {
 rewrite ^ https://sulao.cn/nginx/? permanent;
 }

目录跳转到新目录

if ( $request_filename ~ nginx/ ) {
 rewrite ^ http://nginx.sulao.cn/? permanent;
}

一个比较复杂的重定向实例:

rewrite ^([^\.]*)/html/2015/(\w+)_([0-9]+)/(.*)$ $1/html/$2/$4  permanent;

将三级目录转向到指定二级目录

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/161.html

我要评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。