【问题标题】:301 Redirect Specific Pages in Nginx BEFORE Redirecting Entire Domain/Catch All301 在重定向整个域/全部捕获之前重定向 Nginx 中的特定页面
【发布时间】:2018-07-21 12:15:46
【问题描述】:

我在 nginx 中有数千页到 301 重定向。我可以使用

return 301 https://www.newdomain.com$request_uri;

但是,我希望将大约 6 个页面重定向到新域上已更改的 slug/路径,例如

   location /old-path/ {
   rewrite ^ https://www.newdomain.com/newpath/ permanent;
   }

我已经尝试过,但无法确定如何首先重定向这 6 个,具体而言,然后将 catch all 规则应用于其他所有内容。

目前,我仅使用 catch all 重定向旧域,然后在新域上使用 301 将 6 个帖子更改为新路径(这 6 个帖子总共有 2 个重定向)。

我想实现上述不仅是为了将这 6 个页面的重定向减少到 1,而且因为我想将 6 个页面之一重定向到新域上的新路径,但它的旧路径仍然存在作为新域上的(新)页面(因此我需要将其重定向到旧域,而不是新域)。

【问题讨论】:

    标签: redirect nginx url-redirection http-status-code-301


    【解决方案1】:

    rewrite module 的指令是按顺序执行的,因此整个过程可以单独使用rewritereturn 指令完成,而无需将它们包装在location 块中。例如:

    server {
        ...
        rewrite ^/old-path/ https://www.newdomain.com/newpath/ permanent;
        rewrite ^/...       https://www.newdomain.com/.../     permanent;
        return 301          https://www.newdomain.com$request_uri;
    }
    

    如果您将rewrite 语句包装在location 块中,则return 语句也必须包装在location 块中。例如:

    location / {
        return 301 https://www.newdomain.com$request_uri;
    }
    location /old-path/ {
        rewrite ^ https://www.newdomain.com/newpath/ permanent;
    }
    

    【讨论】:

    • 谢谢@richard,这似乎奏效了!我注意到,如果我有诸如rewrite ^/archive-page/ https://www.newdomain.com/new1/new2/ permanent;rewrite ^/archive-page/old1/ https://www.newdomain.com/new3/ permanent; 之类的规则,那么 /archive-page/ 之后的所有内容(例如 /archive-page/old1/)也将被重定向到第一条规则。有什么办法吗?
    • 您好,我想我已经修复了上述问题:if ($request_uri = "/archive1/") { rewrite ^ https://www.newdomain.com/new1/new2/ permanent; } if ($request_uri = "/archive1") { rewrite ^ https://www.newdomain.com/new1/new2/ permanent; } 我实现了这一点,并且 /archive1/ 之后的所有内容(例如 /archive1/324324/)都根据我的其他规则正确重定向跨度>
    • 您可以根据需要使正则表达式尽可能具体,更具体的正则表达式应该放在不太具体的正则表达式之前。如果您想要完全匹配,请在正则表达式中添加尾随 $
    • 对不起,我不太明白最后一部分 - 目前conf文件中规则的顺序是: 1. if语句规则(其中2条) 2. 重写规则(大约60条) ) 3.返回规则(1条规则)。我应该改变那个顺序吗?此外,我认为您是说我可以使用$ 优化事物,但再次抱歉,我真的不知道该具体放在哪里。它会替换我的 if 语句中的 "" 吗?或者如果我使用$,我是否不需要 if 语句(并且可以执行正常的重写规则) - 所以它会是rewrite ^/archive1/$ ... permanent;
    • if ($request_uri = "/archive1/")^/archive1/$ 写为正则表达式时相同。所以你的 if 块可以替换为 rewrite ^/archive1/$ https://www.newdomain.com/new1/new2/ permanent;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2020-10-29
    • 2020-03-08
    • 2014-06-24
    相关资源
    最近更新 更多