如何在nginx中重定向单个URL?


111

我正在重组url结构。我需要为特定网址设置重定向规则-我正在使用NGINX。

基本上是这样的:

http://example.com/issue1 --> http://example.com/shop/issues/custom_issue_name1
http://example.com/issue2 --> http://example.com/shop/issues/custom_issue_name2
http://example.com/issue3 --> http://example.com/shop/issues/custom_issue_name3

谢谢!


3
是“ isse”还是“ issue”?答案假定为“问题” ...
Matthew Wilcoxson 2014年

这是问题,修正了错字
tokmak

Answers:


122

将其放在您的服务器指令中:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

或复制它:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...

139
location ~ /issue([0-9]+) {
    return 301 http://example.com/shop/issues/custom_isse_name$1;
}

@Cybolicl我刚刚在Docker映像上使用该版本进行了测试,这1.10.3很好,您能以某种方式提供您的配置文件吗?您可能缺少了一些东西。
Mohammad AbuShady

34

如果您需要重复多个重定向,则可以考虑使用地图:

# map is outside of server block
map $uri $redirect_uri {
    ~^/issue1/?$    http://example.com/shop/issues/custom_isse_name1;
    ~^/issue2/?$    http://example.com/shop/issues/custom_isse_name2;
    ~^/issue3/?$    http://example.com/shop/issues/custom_isse_name3;
    # ... or put these in an included file
}

location / {
    try_files $uri $uri/ @redirect-map;
}

location @redirect-map {
    if ($redirect_uri) {  # redirect if the variable is defined
        return 301 $redirect_uri;
    }
}

4
这就是我在这里寻找的内容-将它们放入包含的文件中是一种替换apache中充满RewriteRules的.htaccess文件的好方法。
来自Qaribou 2015年

3
您如何将这种地图方法与现有位置/ ... proxy_pass类型设置结合起来?
Michael Dausmann

在该@redirect-map位置,您可以尝试if ($redirect_uri = "") {return 404;}使用proxy_pass东西。可能需要使用重写$redirect_uri
Cole Tierney 2015年

location根据您的设置,可能需要用它来代替2 个块。例如,这适用于Craft CMS。location ~ ^(.*)$ { if ($redirect_uri) { # redirect if the variable is defined return 301 $redirect_uri; } try_files $uri $uri/ /index.php?p=$uri&$args; }
luwes
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.