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



$ sudo vim /etc/nginx/nginx.conf


2. Block IP access

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

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;


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 != "") {
    return 301;


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!