Skip to main content
null 💻 notes

Nginx - Proper 443 (HTTPS) and WWW Redirecting

Recently I was working on a project that required an Nginx server to redirect all traffic to https://domain.com, and by all traffic I mean anything that did not start with https://domain.com needed to be rewritten to that. This included:

To do this, the configuation file on Nginx should look like this:

server {
      listen 80;
      server_name domain.com www.domain.com;
      return 301 https://domain.com$request_uri;
}
server {
      listen 443 ssl;
      ssl on;
      ssl_certificate /path/to/your.crt;
      ssl_certificate_key /path/to/your.key;

      server_name www.domain.com;
      return 301 https://domain.com$request_uri;
}
server {
      listen 443 ssl;
      ssl on;
      ssl_certificate /path/to/your.crt;
      ssl_certificate_key /path/to/your.key;
      server_name domain.com;
}

Note that you can switch around the settings for the two two 443 blocks and instead force it to write to www; I'm a fan of excluding it.