Simple NGINX setup for multiple services

Main page

This assumes that you are using certbot and have a wildcard certificate.

You'll want to store the main nginx file in /etc/nginx/conf.d/main.conf

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    root /var/www/html;
    server_name  *.yadamiel.com yadamiel.com;

    listen 443 ssl;

    # RSA cert
    ssl_certificate /etc/letsencrypt/live/yadamiel.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/yadamiel.com/privkey.pem; # managed by Certbot

    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

    # Redirect non-https traffic to https
    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot

     location / {
        resolver 127.0.0.1 valid=30s;
        proxy_pass http://127.0.0.1:8081; # my dashboard page
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

This is where my certificate is saved and all unknow pages are redirected to my frontpage/dasboard.

Subdomains

For the subdomains, first we're going to set up a snippet which can be added to multiple config files.

Snippets are normally stored in /etc/nginx/snippets/. Create a new file there called proxy_headers.conf and add the following in it:

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

These are the relevant headers for reverse-proxying most services.

Then subdomains can be configured like this in /etc/nginx/sites-avaliable/servicename.conf (create one file per service)

server {
    listen         80;
    server_name    servicename.yadamiel.com; # here is where the subdomain needs to be defined
    return         301 https://$server_name$request_uri;
} # this redirects to https

server {
    listen 443 ssl http2;
    server_name servicename.yadamiel.com; # here is where the subdomain needs to be defined
    client_max_body_size 128M;

    location / {
        proxy_pass http://127.0.0.1:8080; # here you need to define the port this service is running on
        include snippets/proxy_headers.conf; # here we insert the previusly defined snippet
    }
}

This then needs to be symlinked into /etc/nginx/sites-enabled/ using ln -s /etc/nginx/sites-available/servicename.conf /etc/nginx/sites-enabled/servicename

Then you can reload nginx by checking if the config is correct using nginx -t and reloading using systemctl reload nginx

Have fun!