Skip to content

Instantly share code, notes, and snippets.

Last active February 26, 2024 18:30
  • Star 18 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save gmolveau/5e5b0bd2773100d85d9302d0fa96632d to your computer and use it in GitHub Desktop.
How to use nginx as a reverse-proxy with letsencrypt

How to use nginx as a reverse-proxy with letsencrypt

Your infrastructure

generated via plantuml



Adding a new app (subdomain)

this example shows how to add a new app, served locally (via docker) on for the subdomain

  • create a new file for this app : sudo touch /etc/nginx/sites-available/YOUR_SUBDOMAIN

  • and activate this file : sudo ln -s /etc/nginx/sites-available/YOUR_SUBDOMAIN /etc/nginx/sites-enabled/YOUR_SUBDOMAIN

  • then edit the file with : sudo nano /etc/nginx/sites-available/YOUR_SUBDOMAIN

server {
    # HTTP configuration
    listen 80;
    listen [::]:80;
    # HTTP to HTTPS
    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot
    # HTTPS configuration
    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    location / {
        proxy_redirect                      off;
        proxy_set_header  Host              $http_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_read_timeout                  900;

don't worry if those files don't exist yet, they will be created in just a moment.

  • Don't forget to change :
    • by your (sub)domain
    • the info in proxy_pass

Generating letsencrypt certificates

  • Run the next command to generate your certificates :
    • sudo certbot --nginx

Managing multiple apps

  • If you want to add another app (for another app/subdomain), simply repeat the process in Adding a new app.

Automatic certificates refreshing

  • Create a new file in /etc/cron.weekly : sudo touch /etc/cron.weekly/certbot
  • Make it executable : sudo chmod +x /etc/cron.weekly/certbot
  • And add this code :
certbot renew
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment