Redirect http to https with nginx

Create two server environments, one for port 80 (http) and one for port 443 (https). Have the http environment do nothing but redirect to the other one:

server {
        listen 80;
        listen [::]:80;
        server_name yesterdayscoffee.de www.yesterdayscoffee.de;
        return 301 https://$server_name$request_uri;
}
server {
        listen 443 ssl;
        listen [::]:443 ssl;

... all the rest of your configuration

}

HTTPS with LetsEncrypt and nginx

First install Certbot on your computer using the instructions at https://certbot.eff.org/

Then you can create a certificate for the page www.yesterdayscoffee.de (with and without www) like this:

certbot -d yesterdayscoffee.de -d www.yesterdayscoffee.de --manual --preferred-challenges http certonly

During the proces, you will be asked to create a file with a specific content at a specific location on your web server (this is for the option http, there are other ways of proving that you control the domain). Once you have done this and everything is fine, the certificate will be created.

The certificate consists of a bunch of files in a location the certbot tells you. You will probably need to put two files on the server: The private key in privkey.pem and the certificate file fullchain.pem. As a location, the folder /etc/letsencrypt/live/ is suggested.

Now you have the certificate, the next step is to tell the web server to use them for your web page. We are using nginx with the configuration file for our web page yesterdayscoffee.de at the default location /etc/nginx/sites-available/. The only thing to do is to add the port 443 for the https protocol and specify the location of the certificate files. These are the lines:

listen 443 ssl;
listen [::]:443 ssl;

ssl_certificate /etc/letsencrypt/live/www.yesterdayscoffee.de/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/www.yesterdayscoffee.de/privkey.pem;

Restart nginx for the changes to take effect with:

sudo /etc/init.d/nginx restart

You may need to tell your firewall to open the https port for nginx:

sudo ufw allow 'Nginx HTTPS'

That’s it! Now it should work. Coming up: How to redirect http to https and how to renew certificates (which with letsencrypt you have to do every 90 days).