SSL configuration for nginx   Oct 22, 2014

Making your nginx-powered site use SSL can be very simple and in this post I'll describe the basic steps.


You can obtain a server SSL cert for free from StartSSL, the process is a bit finicky but free is free. Once you've obtained your SSL Cert and private key you need to upload them to your web server and put them in an appropriate location. You also need to point your web server configuration at the cert and key and set it up to accept https connections (port 443 is the standard port). An SSL cert is issued by a Certification Authority (or CA) and the common browsers have a set of CA certs that they trust. This means that when a cert is issued for your server from a trusted CA, the browser therefore trusts your cert. However, due to the way certificate signing is done, certs are normally signed by what's called a Subordinate CA and although the Root CA's cert may be trusted by the browser, the Subordinate CA cert may not be present. So it's good practice to include the Sub CA cert along with your server's cert.

To merge the Sub CA and Server certs, on linux you can just concatenate them like so:cat server.crt sub-ca.crt >> bundle.crt. This yields a new file called bundle.crt which contains both certs with the server cert first and the sub CA cert second. The order is important so make sure it's done this way, Firefox in particular seems to be sensitive to this. So now you just need to set up your web server to serve over https and use the cert and key.

Let's say you have an nginx.conf like this one below

server {
    listen 80;
    server_tokens off;
    server_name www.mysite.com mysite.com;
    access_log /opt/mysite/logs/nginx-access.log;
    error_log /opt/mysite/logs/nginx-error.log;
}

You just need to add an additional server block so your nginx config looks like this one below.

server {
    listen 80;
    server_tokens off;
    server_name www.mysite.com mysite.com;
    access_log /opt/mysite/logs/nginx-access.log;
    error_log /opt/mysite/logs/nginx-error.log;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_tokens off;
    server_name  www.mysite.com mysite.com;
    ssl_certificate /etc/nginx/ssl/bundle.crt;
    ssl_certificate_key /etc/nginx/ssl/www.mysite.com.key.pem;
    access_log /opt/mysite/logs/nginx-access.log;
    error_log /opt/mysite/logs/nginx-error.log;
}
The 301 response tells the browser there is a permanent redirect from the http connection on port 80 to the https connection on port 443. It also tells nginx where to find the cert and private key for the https connection. In a further update I'll describe where and how to get these SSL certs for free and the proper way to load them onto your server.

Tags for this post:

 Back