NGINX redirect ip to domain

How to Redirect IP to Domain URL in NGINX

Sometimes you may need to redirect IP to domain URL in NGINX. Unless the IP address automatically redirects to domain name, your website will be accessible via IP address as well as domain name, leading to a problem of duplicate content. Here are the steps to redirect IP address to domain URL in NGINX server.


How to Redirect IP to Domain URL in NGINX

Here is how to redirect IP to domain URL in NGINX.


1. Open NGINX configuration

Open terminal and run the following command to open NGINX configuration. If your NGINX configuration file is located somewhere else, then please update the file path below as per your requirement.

$ sudo vi /etc/nginx/nginx.conf


2. Redirect IP to Domain URL

Let us say the IP address of your website is 45.43.42.41 and domain is www.example.com. Add the following server block to NGINX configuration file.

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

In the above case, we create a separate server block that listens to port 80. Since our server_name is same as IP address, this NGINX server will listen to all requests sent to your website’s IP address. The last line redirects all requests received by this server block to your domain https://www.example.com. We return a 301 response code for permanent redirect.


3. Restart NGINX server

Run the following command to check syntax of your updated config file.

$ sudo nginx -t

If there are no errors, run the following command to restart NGINX server.

$ sudo service nginx reload #debian/ubuntu
$ systemctl restart nginx #redhat/centos

It is important to make sure that your website’s IP address automatically redirects to your domain. Otherwise, your website users will be able to view your website both via its IP address as well as domain name, which can be confusing.

It will also result in duplicate content penalty as search engines may consider your website to contain duplicate content. This is because search engines will see your domain and IP address as two separate entities with same content. Also, if there are some backlinks to your IP address, and some links to your domain they won’t be consolidated as far as SEO is concerned, and it can lower your website’s rankings in search engine.

Typically, the redirection of IP to domain is done in domain registrar by adding an A record for it and does not require you to make any changes in NGINX. However, if you don’t have access to your domain registrar’s settings then you can follow the above steps for it.

Also read:

Redirect IP to Domain in Apache
How to Fix Mixed Content/Insecure Content in Apache/PHP
How to Force HTTPS in .htaccess in Apache
How to Set Content-Disposition Header to Attachment in Apache
How to Get Package Details in Ubuntu

Leave a Reply

Your email address will not be published. Required fields are marked *