How to Redirect Non-WWW to WWW in NGINX


redirect non www to www in nginx

Search engines view www and non-www versions of your website as two separate entities altogether. So the back links received to one of them doesn’t really help the other version. Also, there is a possibility that Google sees the two versions as duplicates. So if your www version of your website has more backlinks, it might be a good idea to redirect non-www to www version to consolidate SEO juice. NGINX makes it easy to consolidate the 2 versions of your website. Here’s how to redirect non-www to www in NGINX web server.

 

How to Redirect Non-WWW to WWW in NGINX

Here are the steps to redirect non-www to www in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor. You will find it at one of the following locations, depending on your installation type


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

 


$ sudo vim /etc/nginx/nginx.conf

 

2. Redirect Non-www to www

We need to create 2 separate server blocks in NGINX config file – one for www and the other for non-www. In the server block for non-www we add a redirect directive to direct all the requests to www, like so


server {
 listen 80;
 server_name example.com;
 return 301 http://www.example.com$request_uri;
}

server {
 listen 80;
 server_name www.example.com;
 ...
}

 

If you want to redirect non-www to www using https, then here’s the server config for it


server {
 listen 80;
 server_name www.example.com;
 # $scheme will get the http protocol
 return 301 $scheme://example.com$request_uri;
}

server {
 listen 80;
 server_name example.com;
 location / {

 rewrite ^/cp/login?$ /cp/login.php last;
 ...
 }
}

 

If you have already created server blocks in your NGINX config file, then update them to what’s shown above.

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

That’s it! Now NGINX will automatically redirect non-www to www. This will tell search engines that they are both the same website and not duplicates.

 

 

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!