Tim's Blog

Information, Technology, Security, and other stuff.

Forcing SSL on Nginx

Published 2015-02-01

So I was looking through the domain names that I own, and found I had purchased an SSL cert and never claimed it.

So now this site is SSL-Enabled with a trusted cert, rather than the self-signed cert I was using before.

It took me a couple of goes to get forced-SSL working though, as most of the Nginx tutorials weren't working for me. I got stuck in a couple of redirect loops or nginx would refuse to start. In all honesty I really have little clue as to what I'm doing with nginx, as it's not something I really look at very often.

In any case, this is the configuration that got it working for me in the end (thanks to this digital ocean answer). I simply just had to add the if ($scheme = http) part at the end of my server config file:

# editing /etc/nginx/conf.d/timothy-quinn.conf
server { 
	listen 80;
	listen 443 ssl;
	server_name timothy-quinn.com www.timothy-quinn.com;
    ssl_certificate /path/to/ssl/certificate.crt;
    ssl_certificate_key /path/to/ssl/key.key;
    location / {
    	proxy_set_header        X-Real-IP       $remote_addr;
    	proxy_set_header        Host            $http_host;
        proxy_pass              http://address:port;
    }
    if ($scheme = http) {
            return 301 https://$server_name$request_uri;
    } 
}

Update: Interestingly, I get 502 Gateway errors from Ghost when trying to Publish if I omit the "www" from my site address. I didn't notice this before because I wasn't get redirected to the site with the "www" before. Interesting side-effect.