126

I'm in the process of reorganizing URL structure. I need to setup redirect rules for specific URLs - I'm using Nginx.

Basically Something like this:

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

Thanks!

Syscall
  • 19,327
  • 10
  • 37
  • 52
tokmak
  • 1,489
  • 2
  • 12
  • 16

3 Answers3

148
location ~ /issue([0-9]+) {
    return 301 http://example.com/shop/issues/custom_isse_name$1;
}
Mohammad AbuShady
  • 40,884
  • 11
  • 78
  • 89
  • @Cybolic I just tested this on a docker image with the version `1.10.3` and it was fine, could you provide your config file somehow? You probably are missing something. – Mohammad AbuShady Sep 27 '17 at 09:16
133

Put this in your server directive:

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

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...
BraveNewCurrency
  • 12,654
  • 2
  • 42
  • 50
37

If you need to duplicate more than a few redirects, you might consider using a map:

# 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;
    }
}
srborlongan
  • 4,460
  • 4
  • 26
  • 33
Cole Tierney
  • 9,571
  • 1
  • 27
  • 35
  • 4
    This is what I came here looking for -- putting these in an included file is an excellent way to replace my .htaccess file full of RewriteRules from apache. – Josh from Qaribou Mar 06 '15 at 17:39
  • 3
    how would you combine this map approach with an existing location / ... proxy_pass type setup? – Michael Dausmann Nov 09 '15 at 21:58
  • In the `@redirect-map` location you could try `if ($redirect_uri = "") {return 404;}` followed by proxy_pass stuff. Might need a rewrite using `$redirect_uri`. – Cole Tierney Nov 10 '15 at 23:56
  • This might be needed instead of the 2 `location` blocks depending on your setup. This is for Craft CMS for example. `location ~ ^(.*)$ { if ($redirect_uri) { # redirect if the variable is defined return 301 $redirect_uri; } try_files $uri $uri/ /index.php?p=$uri&$args; }` – luwes Sep 18 '16 at 11:46