How to Redirect IP Request to URL in NGINX


redirect ip request to url in nginx

Sometimes, you may want to redirect IP request to URL for better SEO, or security purposes. You can easily do it in NGINX with just a couple of lines of code. Let us take a look at how to redirect IP request to URL in NGINX.

 

How to Redirect IP Request to URL in NGINX

Here are the steps to redirect IP request to URL 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 request to URL

Let’s say you run a website www.example.com and its IP is 45.45.45.45. You want to redirect all IP requests to a specific URL www.example.com/product, then add the following lines to your NGINX config file

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

In the above code, NGINX will match all requests beginning with your IP and redirect them to your specific URL.

In the above code, the query string from original request will be retained during redirection. If you want all requests to be retained to just remove $request_uri from the return statement.

server {
listen 80;
server_name 45.45.45.45;
return 301 $scheme://www.example.com/product;
}

 

 

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 URL.

 

 

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!