301 Redirects in Nginx
Below you can find a couple ways to create 301 redirects for your Nginx web server.
Non-WWW to WWW Rewrite
To create an Nginx 301 redirect from a non-www domain URL to the www domain URL, place the following code inside of a server {}
code block in your site’s Nginx config file. Replace your_domain.com
with your actual domain name.
if ($host = 'your_domain.com'; ) { rewrite ^/(.*)$ http://www.your_domain.com/$1 permanent; }
WWW to Non-WWW Rewrite
To create a Nginx 301 redirect from a www domain URL to the non-www domain URL, place the following code inside of the server {}
code block in your site’s Nginx config file. Again, replace your_domain.com
with your actual domain.
if ($host = 'www.your_domain.com'; ) { rewrite ^/(.*)$ http://your_domain.com/$1 permanent; }
Alternatively, you can place a new server {}
code block inside of your site’s Nginx config file and create your Nginx 301 redirects like the following.
WWW to Non-WWW Rewrite
server { listen 80; server_name www.your_domain.com; rewrite ^/(.*) http://your_domain.com permanent; }
Non-WWW to WWW Rewrite
server { listen 80; server_name your_domain.com; rewrite ^/(.*) http://www.your_domain.com permanent; }