Random things that interest me.

+

One url Apache-style 301 redirects in nginx

In Apache, you can create an .htaccess file to house 301 Redirect statements, or you can do it in the main config file. It is easy, and common. To change the url that appears in a client browser, as well as tell it where to find something that is no longer located in an original place, you would write something like this for :

Redirect 301 /original_location/

where is where the client is looking for the file, but would not find it, and is what you want used when the original is requested as well as in the future.

Easy, right?

I searched and searched for good documentation on how to do this with nginx. I found great documentation for doing it with a regex, such as this sample code you could put in your site-specific vhost file at /etc/nginx/sites-available/mysampledomain.com for forcing browsers to use the domain name without www.

What I couldn’t find was a simple way to do static redirects, like in my sample above. So, tonight I did some experimenting and figured it out. I hope this helps someone else. Put something like this in your /etc/nginx/sites-available/mysampledomain.com file, in the main server section (see second example following this one).

Post navigation

7 thoughts on “One url Apache-style 301 redirects in nginx”

I’ll anticipate the “why?” question. I have a few pages on this blog that are in a regular rotation on StumbleUpon and previously on Digg that still get traffic using URLs that haven’t existed in a long time, since I changed from using DotClear as my blogging platform and went to WordPress a long time ago.

When I was using Apache, I just put some 301 Redirects in an .htaccess file and “no big deal.” The old links still worked, sending visitors to the new location.

Switching to nginx this week, I lost that ability and couldn’t find any good documentation on how to do this (in English, it might exist in Russian…), so I decided to experiment. Hopefully someone else with a similar need will find the info useful. If not, at least I have it recorded for when/if I need it again.

Many thanks Matthew – this is exactly what I was looking for. I had a slew of 301 redirects in an .htaccess file, and didn’t find any other clear explanation of how to recreate them in nginx until landing here. I put the location entries right in /etc/nginx/nginx.conf instead of /etc/nginx/sites-available/example.com – worked great. Thanks again!