How to Prevent Direct IP Access in NGINX


block direct ip access nginx

Sometimes, you need to block people from accessing your website via its IP address, and allow access only through your domain name. There are multiple ways to do this in NGINX web server. Let us take a look at how to prevent direct IP access in NGINX.

 

How to Prevent Direct IP Access in NGINX

Here are the steps to prevent direct IP access 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. Block IP access

Let’s say you run a website example.com and don’t want people to access your site by its IP address 54.54.54.54

If you want to redirect visitors who access your site using its IP to your domain, then add the following lines in your server block

server {
        listen 80;
        server_name IP_ADDRESS;
        return 301 http://example.com;
}

 

If you want to return 403/404 response instead, use a wildcard server block that will catch all requests that don’t have your domain name and return 404/403 response as per your requirement.

server {
    listen 80;
    server_name _;
    return 404;
}

 

You can also use if condition in your server block to check the host name and redirect/block them but the above code is a lot simpler.

if ($http_host != "example.com") {
    return 301 example.com;
}

 

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 detect IP access and block/redirect them as you have configured in your NGINX web server.

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!