Setting up SSL with nginx including redirects from non HTTPS traffic

S

In an attempt to improve security and privacy on the Internet, Google is encouraging websites to secure their site with an SSL certificate, aka https:// instead of http://
As you may have noticed, I just officially updated my domain to be under SSL. As I described in my It’s LEMP not LAMP post that I use nginx for my web server. I thought I would share how easily I was able to convert my website to use SSL with nginx.

Before you begin, be sure you have already created your SSL certificate and have your certificate and private key files ready and uploaded to your server (I got my SSL cert free with my domain registration at Porkbun).

Common nginx configuration

Before upgrading I had the basic server configuration as follows:

[code]
server {
listen 80;
server_name www.endyourif.com;

# remainder of regular server setup
}
[/code]

The above is just a subset of the server configuration as there is much more configuration to point to root directories and all of that jazz.

Setting nginx SSL Configuration

To change this to SSL, I changed the above setup as follows:

[code]
server {
listen 443;
server_name www.endyourif.com;

ssl on;
ssl_certificate /link/to/my/endyourif.cert;
ssl_certificate_key /link/to/my/endyourif.key;

# remainder of regular server setup
}
[/code]

In the above example you will need to change the ssl_certificate and ssl_certificate_key to where the files are located on your server.

As a final step, I wanted to ensure that all of my traffic always go to SSL. To accomplish this I added the following additional server config:

[code]
server {
listen 80;
server_name endyourif.com www.endyourif.com;
return 301 https://www.endyourif.com$request_uri;
}
[/code]

The following config will redirect any traffic to http://endyourif.com or http://www.endyourif.com to https://www.endyourif.com. The end part $request_uri ensures that it redirects the visitor to the same page they are currently on.

Redirecting non-www to www with SSL

And finally I also want https://endyourif.com to go to https://www.endyourif.com, so I added one additional server config as follows:

[code]
server {
listen 443;
server_name endyourif.com;

ssl on;
ssl_certificate /link/to/my/endyourif.cert;
ssl_certificate_key /link/to/my/endyourif.key;

return 301 https://www.endyourif.com$request_uri;
}
[/code]

I slightly learned the hard way with this last configuration that I had to include the same ssl information that I used in the original server configuration. I wrongly assumed that the redirect would happen immediately. Instead nginx served up my default ssl certificate which did not match this domain.

About the author

By Jamie

My Books