How to Redirect IP Request to Domain in NGINX


redirect ip request to domain in nginx

Sometimes, you want to redirect all requests sent directly to your website’s IP to your domain, for the sake of SEO or security purposes. You can easily accomplish this in NGINX web server with a couple of lines of code. Let us take a look at how to redirect IP request to domain in NGINX.

 

How to Redirect IP Request to Domain in NGINX

Here are the steps to redirect IP request to domain 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 the type of installation


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

$ sudo vim /etc/nginx/nginx.conf

 

2. Redirect IP address to domain name

Let’s say you run a website www.domain.com and its IP address is 54.54.54.54. You want to redirect all requests to 54.54.54.54 to www.domain.com.

So add the following lines to your NGINX config file. We basically create a separate server block to handle requests to your IP address.

server {
listen 80;
server_name 54.54.54.54;
return 301 $scheme://www.domain.com$request_uri;
}

In the above code, NGINX will match all URLs beginning with your IP and redirect them to your domain.

 

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 all requests sent to your IP, to your domain.

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!