End Your If

Helping you solve those tough coding problems!

Setting up SSL with nginx including redirects from non HTTPS traffic Setting up SSL with nginx including redirects from non HTTPS traffic

Published on Feb 6, 2019 by Jamie Munro

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).


Before upgrading I had the basic server configuration as follows:

server {
listen 80;
server_name www.endyourif.com;

# remainder of regular server setup
}

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.
To change this to SSL, I changed the above setup as follows:

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
}

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:

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

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.
And finally I also want https://endyourif.com to go to https://www.endyourif.com, so I added one additional server config as follows:

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;
}

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.

Tags: SEO (Search Engine Optimization) | Optimization | nginx | ssl

My Books
blog comments powered by Disqus