Setting up HTTPS on NGINX with Let's Encrypt
Let's Encrypt
Let's Encrypt is a free CA that aims to make it easy to setup TLS encryption on any domain that you control. It entered public beta on December 3, 2015. If you are willing to use the default CSR that Let's Encrypt generates for you (which includes a 2048 bit RSA key) the process is very straightforward. This means that not only is it a free CA, it is easier to use than any other CA on the planet. However, for the time being, this does assumes that your server is running a modern Linux or BSD variant.
Getting Let's Encrypt
The best way to get Let's Encrypt is to clone their git repository:
$ git clone https://github.com/letsencrypt/letsencrypt
Cloning into 'letsencrypt'...
Getting your certificate
After cloning the Let's Encrypt git repository it is very straightforward to acquire your certificate. Note that you will need to stop any servers that are currently listening on port 443 because letsencrypt-auto will bind to the port to verify that you control the domain. This step must be done as root:
$ cd letsencrypt
$ service nginx stop
# you can add as many sub-domains as you like to this command-line
$ ./letsencrypt-auto certonly --standalone -d domain.com -d www.domain.com
At this point letsencrypt-auto will ask for your email address as well as for you to agree to the terms of service. Afterwards your certificate and key will be symlinked from /etc/letsencrypt/live/domain.com
. Don't forget to restart your webserver with service nginx start
.
Configuring NGINX to use your certificate
You will need to create a server block in your NGINX configuration file to use the certificate and key that you just generated. On my Ubuntu server these configuration files are located in /etc/nginx/sites-available
. You probably want to copy your port 80 block, modify the listen line to be listen 443 ssl;
, and add ssl_certificate
and ssl_certificate_key
lines. Alternatively, you can add these listen
, ssl_certificate
and ssl_certificate_key
lines to an exisitng server block. Here is an example of what it might look like when you are done:
server {
listen 443 ssl;
server_name www.domain.com;
ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem;
...
}
At this point you can service nginx restart
and you should be up and running!
Configuring NGINX to automatically redirect HTTP traffic to HTTPS
If desired you can configure NGINX to redirect all HTTP traffic to HTTPS. Replace your HTTP server block with one that looks like this:
server {
listen 80;
server_name www.domain.com;
return 302 https://www.domain.com$request_uri;
}
Don't forget to service nginx restart
.