Blocking Subdomains via Nginx Configuration

Overview 

Your current configuration allows specific domains to reach the app server and you noticed that subdomains not included in the configuration are also reaching the server. You wish to know how to block these subdomains. For example, the server_name in your configuration includes www.domain.com. You wish to block subdomain.domain.com from reaching the app server. This article describes the process to achieve this. 

 

Solution

By default, Nginx will route any requests reaching it to either the first server block with aserver_namematching the request host or just the first server block full stop for requests without a matchingserver_name.

This means that any domains pointed to the IP of the instance/environment will reach the application.

In order to prevent this, you will need to add anotherserverblock (or blocks in the case of SSL listeners needed too) to theholos.conffile to reject any domains not specifically listed in the configuration.

These would have the samelistenconfiguration but server_namecould either be_for a wildcard or specific domains as required. It would thenreturnthe required response instead of sending requests onto the app. You can configure the response to be 404 (not found), 403 (denied), or 444 (no response) as you prefer.

For example:

server {
    listen 8081 proxy_protocol; # xLB Load Balancer port 8081
    listen 8091 proxy_protocol; # HAproxy port 8091
    server_name _;
    return 444;
}

When using the _ wildcard, this server needs to be the first listed in the configuration. Requests without a matchingserver_namedefined in later blocks in the configuration are directed to the firstserver, as it is the default one. 

Comments

Article is closed for comments.