How to Redirect IP Request to Directory in NGINX


redirect ip request to directory in nginx

Sometimes, you may want to redirect IP request to directory 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 directory in NGINX.

 

How to Redirect IP Request to Directory in NGINX

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

For example, a request to 45.45.45.45/login.php will be redirected to www.example.com/product/login.php

If you want to redirect all these requests to the domain, then just remove the directory name from return statement above.

 

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

 

 

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!