Nginx reverse proxy and certbot setup on a Linux Server

Posted on
software nginx certbot linux ubuntu reverse proxy

A few months ago, I ordered a new virtual server with Ubuntu 22.04 Linux because my old one was out of support. Instead of using Plesk to manage everything I wanted to take a vanilla approach. The idea is to make everything scriptable and automate as much as possible. I wanted to avoid the additional attack surface a management software like Plesk or cPanel brings into the game.

Every application that runs on the server is packaged in a normal debian-package. For the web applications, I provide a postinst script to set up the nginx reverse proxy and also set up certbot to provide and auto-renew a LetsEncrypt SSL/TLS Certificate.

I came up with the following script. It does not take into account the various faults and errors that could occur, but it should be a good start and so far works quite well.

#!/bin/sh
set -e

echo "Ensure systemd vhost directory exists"
VHOST_DIRECTORY="/var/www/vhosts/yourdomain.de"
if [ ! -d "$VHOST_DIRECTORY" ]; then
    sudo mkdir -p "$VHOST_DIRECTORY"
fi

echo "Setup nginx website configuration..." 
FILE="/etc/nginx/sites-available/yourdomain.de"
OUTPUT="
server {
    listen 80;
    listen [::]:80;

    server_name yourdomain.de www.yourdomain.de;
        
    location / {
        proxy_pass http://127.0.0.1:9020;
        include proxy_params;
    }
}
"

if [ ! -e "$FILE" ]; then 
    echo $FILE
    sudo touch $FILE
    sudo echo "$OUTPUT" > $FILE
    sudo ln -s $FILE /etc/nginx/sites-enabled/
fi


echo "Setup certificate for website..."
FULLCHAIN="/etc/letsencrypt/live/yourdomain.de/fullchain.pem"
KEY="/etc/letsencrypt/live/yourdomain.de/privkey.pem"

if [ ! -e "$FULLCHAIN" ] && [ ! -e "$KEY" ]; then 
    sudo certbot --nginx -d yourdomain.de -n -m email@provider.de
fi

#DEBHELPER#