Question

How can I do 301 Redirect in nginx for 200 URLs?

I have 200 URLs that I need to redirect to new URLs e.g. http://abc.com/one/p-SF10 -----> http://abc.com/one/p-SF134 http://abc.com/one/p-SM28 -----> http://abc.com/one/p-SM28 http://abc.com/one/p-KH83 -----> http://abc.com/one/p-KH194

On Apache it was very simple to do in .htaccess like:

Redirect 301 /one/p-SF10 http://www.abc.com/one/p-SF134
Redirect 301 /one/p-SM28 http://www.abc.com/one/p-SM28
Redirect 301 /onep-KH83 http://www.abc.com/one/p-KH194

I found one of the guides with following lines:

if ( $request_filename ~ oldpage/ ) {
rewrite ^ http://www.domain.com/newpage/? permanent;
}

My question here is do I need to create these 200 ‘if conditions’? Wouldn’t it create a huge conditional loop and overload my server?

Server configuration: I installed Nginx+php-fpm using VestCP and set the nginx template to wordpress from within VestCP which configured my nginx.conf automatically.


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

You are right to want to avoid using if conditions here, luckily you can avoid them completely by doing the matching with a regex right in the rewrite directive. For example:

rewrite ^/path/to/old $scheme://$host/new/url permanent;

This blog post from Nginx themselves is a good read on the different ways to create rewites and redirects with Nginx and when to use them.