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;

    # ...
}
  • Why doesn't nginx start? – Michael Hampton Jul 3 '20 at 3:02
  • "[emerg] 11380#2432: no "ssl_certificate" is defined for the "listen ... ssl" directive in D:\Web Server\nginx 1.19.0/conf/nginx.conf:87" Which is the first server block above. – Nya Nguyen Jul 3 '20 at 3:13
  • Well, you do need an SSL certificate! – Michael Hampton Jul 3 '20 at 3:20
  • I do have a certificate for each server block that specifies a domain. – Nya Nguyen Jul 3 '20 at 3:25
  • 1
    You have to have SSL certificates for every server block that uses SSL! – Michael Hampton Jul 3 '20 at 3:25
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.

  • My goal was to see if there was a way to redirect any https non-www request to 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. – Nya Nguyen Jul 3 '20 at 6: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 3 '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 3 '20 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.