City of Light Discovering the Metaverse
Discovering the Metaverse

Redirect www to non-www URLs on Nginx

I am using Nginx on Linode Cloud, and I want to redirect www to Non-www in a web browser, and be presented with the same content. There’s variety of ways to set this up, i choose “Permanent Redirect”, also called “301 redirect”, and can be easily set up by properly configuring your DNS records and Nginx server blocks.

Configure DNS Records

First, use the @ symbol to create A record that points your domain to the IP address that your specified.

Next, add another A record with “www” as the hostname, and specify the same IP address.

It should look something like this:

Checking DNS A records:

[root@kenmarch ~]# dig +nocmd kenmarch.com a +noall +answer
kenmarch.com. 0 IN A 172.104.94.221

As you see, the kenmarch.com A record maps to the 172.104.94.221 IP address.

Configure Nginx redirect

In order to perform the 301 redirect, i setup a new Nginx server block that points to my original server block.

[root@kenmarch ~]# vi /etc/nginx/conf.d/redirect.conf

insert this configuration:

server {
    server_name www.kenmarch.com;
    return 301 $scheme://kenmarch.com$request_uri;
}

Save and exit. This configures Nginx to redirect request to “www.kenmarch.com” to “kenmarch.com“.

Before I acutually restart the Nginx service, just check whether its configuration syntax is correct, run the following command:

[root@kenmarch ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

To make the changes take effect, restart Nginx by entering following command:

[root@kenmarch ~]# systemctl restart nginx

Confirm Changes

www to non-www redirection test

[root@kenmarch ~]# curl -I www.kenmarch.com
HTTP/1.1 301 Moved Permanently
Server: nginx/1.20.2
Date: Mon, 04 Apr 2022 05:45:48 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://kenmarch.com/