redirect non-www to www and http to https at the same time

I’ve tried to achieve the following redirects

http://domain.com     -> https://www.domain.com
http://www.domain.com -> https://www.domain.com
https://domain.com    -> https://www.domain.com

So basically http -> https and non-www -> www combined.

Here is my nginx.conf:

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

server {
    listen 443 ssl;
    server_name www.domain.com;

    ssl_certificate /data/unified.crt;
    ssl_certificate_key /data/my-private-decrypted.key;

    location / {
      proxy_pass http://domain.com:3000;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_cache_bypass $http_upgrade;
    }
}

With it, the following redirect is failing

https://domain.com -> https://www.domain.com

What am I doing wrong and how do I add support for that redirect?

Answer

I had to add another server block for https://domain.com

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

server {
  listen 443 ssl;
  server_name domain.com;

  ssl_certificate /data/unified.crt;
  ssl_certificate_key /data/my-private-decrypted.key;

  return 301 https://www.domain.com$request_uri;
}

server {
  listen 443 ssl;
  server_name www.domain.com;

  ssl_certificate /data/unified.crt;
  ssl_certificate_key /data/my-private-decrypted.key;

  location / {
    proxy_pass http://domain.com:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  }
}

Attribution
Source : Link , Question Author : shime , Answer Author : shime

Leave a Comment