How to redirect single URL in Nginx?

NginxUrl Rewriting

Nginx Problem Overview


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!

Nginx Solutions


Solution 1 - Nginx

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

Solution 2 - Nginx

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

Solution 3 - Nginx

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontokmakView Question on Stackoverflow
Solution 1 - NginxMohammad AbuShadyView Answer on Stackoverflow
Solution 2 - NginxBraveNewCurrencyView Answer on Stackoverflow
Solution 3 - NginxCole TierneyView Answer on Stackoverflow