How to handle requests to non-existent subdomains with Nginx

in flag

Here's my Nginx configuration for my domain which serves a trivial static website.

server {
    root /var/www/;

    index index.html index.htm index.nginx-debian.html;


    location / {
        try_files $uri $uri/ =404;

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot

    ssl_certificate /etc/letsencrypt/live/; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

server {
    listen 80;
    listen [::]:80;
    return 301 https://$host$request_uri;

How do I configure Nginx to return 404 whenever I navigate to a subdomain such as Now I find myself looking at the same page as

I've set a wildcard A record for my domain so I'm expecting all requests ending with to find my server. Do I have to remove the wildcard or can I handle these requests to subdomains with Nginx?

Ivan Shatsky avatar
gr flag
To not repeat myself - check [this]( SO answer, I think you'll find there all the information you needed.
cn flag

Nginx server_name configuration allows regular expressions, or even the simpler * wildcard, see

So either of these two should match any name (not better matched by another block)

server_name *
server_name ~^.+\.example\.com$

(The ~ is required to use a regular expression).

You can even capture parts of the name, and use it in subsequent configuration directives. The above documentation link has examples of that.

And you do need the DNS wildcard otherwise the traffic won't reach your webserver (or if no DNS wildcard, you need specific records for the names you want to resolve, no matter how many of them, and still keep the "wildcard" configuration of Nginx)


Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.