nginx: How to mass permanent redirect from a given list?

后端 未结 2 1864
清歌不尽
清歌不尽 2020-12-05 08:03

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

相关标签:
2条回答
  • 2020-12-05 08:42

    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;
    
    0 讨论(0)
  • 2020-12-05 08:51

    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;
        }
    
        ...
    }
    
    0 讨论(0)
提交回复
热议问题