Nginx redirect one path to another
I'm sure this has been asked before, but I can't find a solution that works.
A website has switched CMS services, but has the same domain, how do I set up an nginx rewrite for a single page?
E.g.
Old Page
http://sitedomain.co.uk/content/unique-page-name
New page
http://sitedomain.co.uk/new-name/unique-page-name
Please note, I don't want everything within the content page to be redirected, but literally just the url mentioned above. I have about 9 redirects to set up, non of which fit in a pattern.
Thanks!
Edit: I found this solution, which seems to be working, except for the fact that it redirects without a slash:
if ( $request_filename ~ content/unique-page-name/ ) {
rewrite ^ http://sitedomain.co.uk/new-name/unique-page-name/? permanent;
}
But this redirects to:
http://sitedomain.co.uknew-name/unique-page-name/
Direct quote from Pitfalls and Common Mistakes: Taxing Rewrites:
By using the return directive we can completely avoid evaluation of regular expression.
Please use return
instead of rewrite
for permanent redirects. Here's my approach to this use-case...
location = /content/unique-page-name {
return 301 /new-name/unique-page-name;
}
Ideally you shouldn't use if statements if you can avoid it. Something like this could work (untested).
location ~ /content/(.*)$ {
rewrite ^ /new-name/$1?$args permanent;
}
I used the following solution:
rewrite ^(/content/unique-page-name)(.*)$ http://sitedomain.co.uk/new-name/unique-page-name/$2 permanent;
Works a treat.