Redirect in NGINX: 301 & 302

NGINX is becoming more popular every second – and it’s because it’s super fast. In this tutorial I’m going to show you the difference between a 301 and 302 redirect in NGINX and how to implement them. But first, let’s know the difference.

301 redirects are what is known as permanent redirects. This tells search engines that the old page has been moved permanently.

302 redirects are temporary redirects. These obviously tell search engines that the page has temporarily moved.

For permanent redirects, search engines will update their search results with the new page and remove the old one from its index. It’s that simple.

How to add a redirect to your NGINX configuration

Lets say you have a page called old.html and you would like to permanently redirect it to new.html – in NGINX you would do this:

location /old.html {
rewrite ^(.*)$ https://mywebsite.com/new.html permanent;
}

To temporarily redirect the page in NGINX you would do this:

location /old.html {
rewrite ^(.*)$ https://mywebsite.com/new.html redirect;
}

You would add either in between the server { } section of your NGINX configuration file.

As you can tell, the only different is the last part of the code used: permanent defines it as 301 and redirect defines it as 302.

NGINX reference: http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite