nginx: How to mass permanent redirect from a given

2020-02-04 03:02发布

问题:

I have about 400 url that will change in the new version and for some reasons I can't repeat the same type of url structure in the new website.

My question is, can I give a url list to nginx (yeah I know the 400 ones), and tell him simply that each one of them are going to another url?

Like I said the url structure will be different so I can't use any type of pattern.

Thanks in advance.

回答1:

If you have a very long list of entries, could be a good idea to keep them outside of the nginx configuration file:

map_hash_bucket_size 256; # see http://nginx.org/en/docs/hash.html

map $request_uri $new_uri {
    include /etc/nginx/oldnew.map; #or any file readable by nginx
}

server {
    listen       80;
    server_name  your_server_name;

    if ($new_uri) {
       return 301 $new_uri;
    }

    ...    
}

/etc/nginx/oldnew.map sample:

/my-old-url /my-new-url;
/old.html /new.html;

Be sure to end each line with a ";" char!

Moreover, if you need to redirect all URLs to another host, you could use:

return 301 http://example.org$new_uri;

Or, if you also need to redirect to another port:

return 301 http://example.org:8080$new_uri;


回答2:

Probably the easiest way to do that is to wrap map directive around your list. The configuration in this case would look like this:

map $request_uri $new_uri {
    default "";
    /old/page1.html /new/page1.html;
    /old/page2.html /new/page2.html;
    ...
}

server {
    ...

    if ($new_uri != "") {
        rewrite ^(.*)$ $new_uri permanent;
    }

    ...
}