Website With HTTPS on a Linux Server: Nginx and Let's Encrypt
This page puts a website on your server with the web server Nginx and a free HTTPS certificate from Let's Encrypt. The same setup also puts a program that runs on your server, for example on port 8000, behind your domain with HTTPS. The steps were tested on Ubuntu 26.04 LTS; run the commands as root.
You need a domain (or subdomain) whose A record points to your server's IP address. Below it is called example.com; use your own everywhere.
1. Install Nginx and Certbot
apt install nginx certbot python3-certbot-nginx ufw allow "Nginx Full"
Nginx Full opens ports 80 and 443 in the ufw firewall; leave the line out if you do not use ufw.
2. Create the Website
Put your files in a folder, here a test page:
mkdir -p /var/www/mysite echo "<h1>Hello from my server</h1>" > /var/www/mysite/index.html
Create the file /etc/nginx/sites-available/mysite:
server {
listen 80;
listen [::]:80;
server_name example.com;
root /var/www/mysite;
index index.html;
}
Switch it on, check the settings and load them:
ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/ nginx -t systemctl reload nginx
nginx -t must answer test is successful. Open http://example.com: you see the test page.
3. Get the HTTPS Certificate
certbot --nginx -d example.com --redirect
The first time, Certbot asks for your e-mail address (for warnings about expiring certificates) and for your agreement to the Let's Encrypt terms. It then gets the certificate, adds it to your Nginx file and sends all http:// visits to https://. At the end it reports Congratulations! You have successfully enabled HTTPS.
The certificate is valid for 90 days, and Certbot renews it by itself. To test the renewal:
certbot renew --dry-run
The answer ends with all simulated renewals succeeded.
Put a Program Behind HTTPS
If a program on your server answers on a port, for example 8000 (see Keep a Program Running on Linux), Nginx can pass the visits on to it. In /etc/nginx/sites-available/mysite, replace the lines root … and index … with:
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
Then run nginx -t and systemctl reload nginx. https://example.com now shows your program. Its port no longer needs to be open in the firewall, because Nginx reaches it on the server itself.
Check that the domain points to the server (ping example.com shows your server's address) and that ports 80 and 443 are open. Let's Encrypt has to reach your server on port 80 to issue the certificate.