0

Is it possible to put a redirect in 1 single server block to redirect any https (port 443) that do not have www to https://www...? I don't want to have to put that redirect in every single server block for each specific domain.

I currently have this, but it is not allowing nginx (in Windows) to start up:

server {
    listen 443 ssl;
    server_name _;

    if ($host !~* ^www\.(.*)$) {
        return 301 https://www.$host$request_uri;
    }
}
server {
    listen       443 ssl;
    server_name  example.com;

    # ...
}
server {
    listen       443 ssl;
    server_name  anotherexample.com;

    # ...
}

1 Answers1

1

Your config needs to look like this:

server {
    listen 443 ssl default_server;
    server_name _;

    ssl_certificate /path/to/$ssl_server_name.crt;
    ssl_certificate_key /path/to/$ssl_server_name.key;

    return 301 https://www.$host$request_uri;
}

You need to have your certificate files with names matching your domains. If your domain is example.com, you need to have example.com.crt and example.com.key.

Furthermore, you need to make sure this is the only default_server block for port 443.

Tero Kilkanen
  • 34,499
  • 3
  • 38
  • 58
  • My goal was to see if there was a way to redirect any https non-www request to https://www and I do not want to specify the actual domain names. If we have to specify the domain name, then it means we have to repeat the same redirect in each server block of each domain. – CelestialEX Jul 03 '20 at 06:44
  • @NyaNguyen You have to specify the domain names in the SSL certificate! So there is no point to any of this. You may as well just have `server` blocks for every name. – Michael Hampton Jul 03 '20 at 14:43
  • You can use the code block for all domains. However, you need either a certificate / key file for each domain, or one certificate that lists all domains in Subject Alternate Name field. Main point is, you always need a TLS certificate that matches the domain, otherwise browser will display security error. – Tero Kilkanen Jul 03 '20 at 14:54