snippetnginxModeratependingCanonical
Nginx reverse proxy configuration patterns
Viewed 0 times
nginx reverse proxyssl terminationload balancingwebsocket proxyproxy_pass
Problem
Need common nginx reverse proxy configurations: SSL termination, load balancing, WebSocket proxying, and caching.
Solution
Nginx reverse proxy patterns:
# Basic reverse proxy
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost: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;
}
}
# SSL termination
server {
listen 443 ssl http2;
server_name api.example.com;
ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
location / {
proxy_pass http://localhost: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;
}
}
# HTTP -> HTTPS redirect
server {
listen 80;
server_name api.example.com;
return 301 https://$host$request_uri;
}
# Load balancing
upstream backend {
least_conn;
server 127.0.0.1:3001;
server 127.0.0.1:3002;
server 127.0.0.1:3003;
}
server {
location / {
proxy_pass http://backend;
}
}
# WebSocket proxy
location /ws {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400;
}
# Static file caching
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
# SPA routing
location / {
try_files $uri $uri/ /index.html;
}Why
Nginx handles SSL termination, load balancing, and static files more efficiently than application servers. It's the standard reverse proxy for most web deployments.
Context
Web server and reverse proxy configuration
Revisions (0)
No revisions yet.