301 Redirect Specific Pages in Nginx BEFORE Redire

2019-07-08 09:57发布

问题:

I have thousands of pages to 301 redirect in nginx. I can achieve this using

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

However, there is approximately 6 pages that I would like to redirect to a changed slug/path on the new domain, eg

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

I have tried but can't see to work out how to redirect these 6 first, specifically, and then have the catch all rule apply to everything else.

At the moment I am redirecting on the old domain using the catch all only, and then have 301s on the new domain changing the 6 posts to the new paths (2 redirects total for these 6 posts).

I would like to achieve the above not only to reduce the redirects to 1 for these 6 pages, but also because I want to redirect one of the 6 pages to a new path on the new domain, but it's old path still exists as a (new) page on the new domain too (therefore I need to redirect it on the old domain, not on the new one).

回答1:

The directives of the rewrite module are executed in order, so the entire process can be accomplished with rewrite and return directives alone, without wrapping them within location blocks. For example:

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

If you wrap the rewrite statements within location blocks, then the return statement must also be wrapped within a location block. For example:

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