How to prevent Nginx from redirecting to the wrong site when there’s a secure certificate error

https://serverfault.com/a/846214

When multiple sites share the same server and there is no default site set in the server config, Nginx will redirect to the first site in the config, if there’s a secure certificate error. Here’s how to fix that, based on the linked answer above.

1 – Create a default zone

As nginx is loading vhosts in ascii order, you should create a 00-default file/symbolic link into your /etc/nginx/sites-enabled.

2 – Fill the default zone

Fill your 00-default with default vhosts. Here is the zone i am using:

server {
    server_name _;
    listen       80  default_server;
    return       404;
}


server {
    listen 443 ssl;
    server_name _;
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    return       404;
}

3 – Create self signed certif, test, and reload

You will need to create a self signed certificate into /etc/nginx/ssl/nginx.crt.

Create a default self signed certificate:

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt

Just a reminder:

  • Test the nginx configuration before reloading/restarting : nginx -t
  • Reload: sudo service nginx reload

Hope it helps.