nginx rewrite 301 设置新旧url对

版权声明:本文为博主原创文章,转载请注明来源。 https://blog.csdn.net/y101101025/article/details/61415085

在百度站长平台-优化与维护-网站改版中提示:在网站改版应添加301规则。
改版规则可以通过正则表达式或新旧URL对的方式添加。
我的旧站点目录比较混乱,有部分的地址,通过新旧URL对的方式添加更加便捷。添加方式只需要在nginx下的location中添加即可

rewrite oldAddress newAddress permanent

代码如下:

server {
    listen       80;
    server_name  sitename1 sitename2;
    location / {
        root   siteroot;
        index  index.html index.htm;
        rewrite oldAddress newAddress permanent;
        rewrite oldAddress2 newAddress2 permanent;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

然后我访问一下不存在的旧地址时,报404错误。

404 Not Found

那么如何实现,出现404的时候重定向到新地址,并能返回301呢?
server中添加下面代码在出现404时不能跳转到新地址,能跳转到首页。先更新下配置,后面再来研究。

error_page 404 = @notfound;
location @notfound {
      return 301 /;
}

后来我修改了下location,变成功了。代码如下:

location /oldurl {
      return 301 /newurl ;
}

完整代码如下:

server {
    listen       80;
    server_name  sitename1 sitename2;
    location / {
        root   siteroot;
        index  index.html index.htm;
    }
    location /games/balls/ {
        return 301 /games/catepuzzles/balls/ ;
    }
}

猜你喜欢

转载自blog.csdn.net/y101101025/article/details/61415085
今日推荐