nginx:如何从给定列表中批量永久重定向?

Rap*_*oux 13 redirect nginx

我有大约400个网址将在新版本中更改,由于某些原因我不能在新网站中重复相同类型的网址结构.

我的问题是,我可以给一个网址列表给nginx(是的,我知道400个),并简单地告诉他,他们每个人都要去另一个网址?

就像我说的url结构会有所不同所以我不能使用任何类型的模式.

提前致谢.

lif*_*foo 25

如果你有一个很长的条目列表,最好将它们放在nginx配置文件之外:

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;
    }

    ...    
}
Run Code Online (Sandbox Code Playgroud)

/etc/nginx/oldnew.map示例:

/my-old-url /my-new-url;
/old.html /new.html;
Run Code Online (Sandbox Code Playgroud)

一定要用";"结束每一行.焦炭!

此外,如果您需要将所有URL重定向到另一个主机,您可以使用:

return 301 http://example.org$new_uri;
Run Code Online (Sandbox Code Playgroud)

或者,如果您还需要重定向到另一个端口:

return 301 http://example.org:8080$new_uri;
Run Code Online (Sandbox Code Playgroud)


Iva*_*lev 7

可能最简单的方法是在您的列表中包含map指令.这种情况下的配置如下所示:

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;
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

  • “default”行有必要吗?文档说“当未指定默认值时,默认结果值将为空字符串。”。 (3认同)