3

I followed this answer https://stackoverflow.com/a/28068250/3108268 but it redirects only from http to https and non www to www, but if I go to my website at https://example.com I get 'your connection is insecure'.

How do I redirect it to https://www?

server{
  listen 443 ssl;
  server_name www.mydomain.com;
  root /www/mydomain.com/;

  ssl    on;
  ssl_certificate /ssl/domain.crt;
  ssl_certificate /ssl/domain.key;
  .
  . 
  .
}

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

server{
  listen 443;
  server_name mydomain.com;
  return 301 https://www.$server_name$request_uri;
} 
user3108268
  • 1,043
  • 3
  • 18
  • 37
  • What if you use `$http_host` instead? `return 301 https://www.$http_host$request_uri;` – ffflabs Nov 09 '17 at 13:38
  • It's just the config I use, I thought it may have different outcomes. I'm sorry it didn't. – ffflabs Nov 09 '17 at 13:48
  • Wait. If your certificate doesn't cover the apex domain `mydomain.com` it's only natural the redirect will never happen. – ffflabs Nov 09 '17 at 13:49
  • Yes. If you navigate to domain.com you'll end up in https:// domain.com which will present the warning instead of actually redirecting to www – ffflabs Nov 09 '17 at 14:28

2 Answers2

2

the third server is missing SSL certificates which is why the browser is saying the connection is insecure.

replace your last two servers with:

# redirect www.mydomain.com to https
server {
  listen 80;
  server_name www.mydomain.com;
  return 301 https://$server_name$request_uri;
}

# redirect mydomain.com to https
server{
  listen 80;
  server_name mydomain.com;
  return 301 https://www.$server_name$request_uri;
} 
Zeragamba
  • 88
  • 1
  • 5
2

A good way to get the correct configuration is using new blocks for each redirect, one from http to https and one to non-www to www.

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

server {
    listen 443 ssl;
    ssl_certificate     /path/to/certificate.crt;
    ssl_certificate_key /path/to/private/key.pem;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    ssl_certificate     /path/to/certificate.crt;
    ssl_certificate_key /path/to/private/key.pem;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    server_name example.com;

    # do the proper handling of the request
}
Carca
  • 564
  • 1
  • 6
  • 16
  • This was just an example of using in your case, don't expect to copy paste and that's all.. You can easily to change variables to your needs. – Carca Nov 10 '17 at 09:39
  • I had some weird issue where only Chrome would fails on some redirects. Breaking it down this way fixed it... thanks! – Will59 Feb 03 '21 at 17:01