Home > Back-end >  nginx catchall interfering with wildcard
nginx catchall interfering with wildcard

Time:09-30

I want to redirect www (and possibly other subdomains) to my https domain. So I wrote a rule

server {
    listen 80;
    server_name *.example.com example.com;
    return 301 https://example.com$request_uri;
}

This didn't work until I removed my catch all entry (pasted below). I want to drop or ignore request from no host or host that don't belong to my machine. How do I get the two rules to play nice with eachother?

server {
    listen          80 default_server;
    listen          [::]:80 default_server;
    listen          443 default_server;
    listen          [::]:443 default_server;
    server_name     _;

    include snippets/snakeoil.conf;

    return          444;
}

CodePudding user response:

You need to listen to 443 port in the first server block and remove the catch-all server_name in the second server block. If Host header is blank or doesn't match with any server block, it'll go to default_server and request will be rejected.

server {
    listen 80;
    listen 443 ssl;
    server_name *.example.com example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen          80 default_server;
    listen          [::]:80 default_server;
    listen          443 default_server;
    listen          [::]:443 default_server;

    include snippets/snakeoil.conf;

    return          444;
}
  • Related