Fix: Nginx and Ubuntu 20.04 Redirect www to non-www

Fix: Nginx and Ubuntu 20.04 Redirect www to non-www

 

Learn how to redirect from www to non-www domain on Nginx and Ubuntu 20.04. Serving your website from one domain, www or non-www is the best as it improves SEO and prevents duplicate content.

What is Nginx

Nginx is a web server that can also be used as a reverse proxy, load balancer, mail proxy, and HTTP cache. It is a high performing, scalable, and highly available server. Many web developers nowadays choose Nginx over Apache because of those features.

Nginx and Ubuntu 20.04 Redirect www to non-www

After setting up your domain name. you'll realize that your website is resolving on both www.example.com and example.com. At a glance, this looks like a very good setup since your users are going to access the website either way. BUT, allowing your domain name to be visited on both www and non-www creates a problem, an SEO problem. Google is going to index both sites separately and finds duplicate content and for that, you'll be penalized.

So, how to fix the problem by making a 301 permanent redirect from www to non-www or vise-versa.

First: Configure DNS Records

To set up 301 redirects, the www or non-www domain must have an A records.

Go to your DNS manager, add an A record with www as the hostname, and will redirect to whatever IP address your website is running on. 

Do the same for the non-www domain by adding an A record with @ as the hostname, and will redirect to the same IP address as above.

Configure Nginx

To do a 301 permanent redirect, you must create a new Nginx server block that points to the original server block.

Open your terminal, or log in to your digital ocean server via ssh and edit your Nginx server block.

sudo nano /etc/nginx/sites-enabled/projectname

Add a server block above the file.

server {
server_name www.example.come; 
return 301 $scheme://example.com$request_uri; 

#Copy all the content of the original server block except server_name 

}

Then remove the www domain from the original server under server_name. If your keep www domain under the server_name section, then your app will keep redirecting.

#Original server block
server {
server_name  example.come;

   ..... ....
}

Restart your Nginx server

sudo service nginx restart

©2021 Workly. Theo Nga