First of all, you might ask where to write these rules. Here are a few basic things to remember:
There is no equivalent of .htaccess in NGINX. NGINX does not allow the use of directory level htaccess type of files to control access. Instead NGINX uses a central configuration file for all the config stuff This config stuff includes rewrite rules and 301 redirect commands You should find the NGINX configuration file and put the rewrite / redirect rules in that file You must restart NGINX server in order to bring any changes into effect. So, after every change, you gotta restart server with service nginx restart command
With these things understood, let’s now see how to implement 301 redirects. As you know, 301 redirects are permanent redirection directives. These rules tell crawlers that a URL has been permanently shifted to a new location.
Redirect www to non-www in NGINX
This is one of the most sought-after redirects. A lot of people also ask if www and non-www addresses have any advantages over each other. To answer this, we have published an article on www vs. non-www URLs. In any case, first of all, you would need to decide which format you prefer. You want to keep your website’s URLs in www format or non-www format. Whichever you choose, stick to one format. Do not mix www and non-www URL formats. The following code takes care of www to non-www redirect in NGINX:
Redirect non-www to www in NGINX
This is for those who prefer www based URLs in their websites.
Transfer Website to a New Domain
If you have decided to take your website to a new domain name, it is advisable to setup the old domain name to 301 redirect to the new domain name. This way, you will not lose your regular traffic from the old domain name.
Directory Level Redirect in NGINX
If you want to redirect all the URLs belonging to one directory to the equivalent URLs in a new directory, here is the 301 redirect command:
Redirect one URL to Another on the Same NGINX Host
This is also called the single page redirection. Here a very specific URL is permanently redirected to another very specific URL. For example:
redirects to
Here is the code for NGINX config file: These NGINX config file rules will help you in keeping your website in order. Please be careful while writing redirection rules because a small mistake can break your website. Also, don’t forget to restart NGINX server after making any change in the config file. Should you have any questions or suggestions related with this topic, please feel free to use the comments area. We will try our best to help you. Thank you for using TechWelkin!