Nginx 1 cheatsheet
Nginx 1: Reverse proxy and TLS
8 common Nginx 1 tasks.
Proxy to an app
Forward requests to an app on port 3000 and pass the original host and client address.
location / {
proxy_pass http://127.0.0.1:3000;
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 WebSockets
Pass the upgrade headers so WebSocket connections work through the proxy.
location /ws/ {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
Redirect HTTP to HTTPS
Send every plain HTTP request to the HTTPS version of the same URL.
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
Get a free TLS certificate
Request a Let's Encrypt certificate and let Certbot edit the Nginx config.
sudo certbot --nginx -d example.com -d www.example.com
Test certificate renewal
Check that automatic renewal will work, without issuing a certificate.
sudo certbot renew --dry-run
Configure a TLS server
Listen on 443 with HTTP/2 and your certificate.
server {
listen 443 ssl;
http2 on;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
}
Rate-limit requests
Allow 10 requests per second per client IP, with a small burst.
# in the http block
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;
# in a server or location block
limit_req zone=perip burst=20 nodelay;
Password-protect a location
Require a username and password from an htpasswd file.
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;