Report this

What is the reason for this report?

How to block access using the Server IP in NGINX?

Posted on February 28, 2019

Greetings community!

I have configured a domain in my DO instance, all very well, the problem lies in being able to access the site using the IP of the Server and I really do not want that, I wish that only the site can be accessed through the domain, what type of configuration requires NGINX? or if it is not NGINX, where can I make this configuration?

Beforehand thank you very much.



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

You can add this server block to your configuration.

server {
    listen      80 default_server;
    server_name "";
    return      444;
}

You need to specify “default_server” parameter so that all non available server requests goes to this server block which throws 444 error. The “default_server” parameter cannot be present in any other server block.

444 : CONNECTION CLOSED WITHOUT RESPONSE

1. Make nginx return an error as default behaviour

Edit the /etc/nginx/sites-available/default config file so it returns a conventional HTTP error (400 Bad Request, 403 Forbidden, 404 Not Found, 503 Service Unavailable) in case the server is queried in any other way than though one of the enabled domains:

(...)

server_name _;

location / {
        return 403;                 ### ADD THIS LINE ###
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;  ### COMMENT THIS LINE ###
}

(...)

Note that alternatively to return 403; you can put deny all; as well.

2. Test config and restart nginx service:

sudo nginx -t
sudo systemctl restart nginx.service

3. Expected result:

# server's response if queried by IP address:
$ curl -I 12.345.678.9
HTTP/1.1 403 Forbidden
Server: nginx/1.22.0 (Ubuntu)
Date: Wed, 16 Nov 2022 01:04:40 GMT
Content-Type: text/html
Content-Length: 162
Connection: keep-alive

This comment has been deleted

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.