🖥️ Server Administration
5 分で読める
Reverse Proxy Setup
Set up Nginx as a reverse proxy for load balancing, SSL termination, and multiple applications.
What Is a Reverse Proxy?
A reverse proxy sits in front of your application servers and handles incoming client requests. It forwards requests to the appropriate backend server and returns the response to the client.
Client → Reverse Proxy (Nginx) → Application Server (Gunicorn, Node.js, etc.)
Why Use a Reverse Proxy?
- SSL termination — Handle HTTPS at the proxy, serve HTTP to backends
- Load balancing — Distribute traffic across multiple application instances
- Static file serving — Serve static assets efficiently without burdening the app
- Security — Hide backend server details, add security headers
- Caching — Cache responses to reduce backend load
Basic Nginx Reverse Proxy
# /etc/nginx/sites-available/myapp
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:8000;
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;
}
location /static/ {
alias /var/www/myapp/staticfiles/;
expires 30d;
}
}
SSL Termination
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.pem;
ssl_certificate_key /etc/ssl/private/example.com.key;
# Modern SSL configuration
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto https;
}
}
# Redirect HTTP to HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
Load Balancing
upstream app_servers {
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
}
server {
listen 80;
location / {
proxy_pass http://app_servers;
}
}
Load balancing methods: - Round-robin (default) — Requests distributed sequentially - Least connections — Sent to server with fewest active connections - IP hash — Same client IP always goes to the same server (sticky sessions)
Security Headers
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
Essential Proxy Headers
Always set these headers so your application knows the real client information:
| Header | Purpose |
|---|---|
X-Real-IP |
Client's actual IP address |
X-Forwarded-For |
Chain of proxy IPs |
X-Forwarded-Proto |
Original protocol (http/https) |
Host |
Original Host header |