กลับไปหน้าสูตร
#nginx#webserver#devops#cheatsheet
Nginx Cheatsheet
รวมคำสั่งและ config Nginx แบบจัดเต็ม: reverse proxy, static, SSL, cache, gzip, security headers, rate limit และ troubleshooting
11 มีนาคม 2569อ่านประมาณ 1 นาที
สารบัญสูตร
Service Commands
| Command | ใช้ทำอะไร |
|---|---|
nginx -v | ดูเวอร์ชัน |
nginx -t | test config |
nginx -T | dump config ทั้งหมด |
sudo systemctl start nginx | start service |
sudo systemctl stop nginx | stop service |
sudo systemctl reload nginx | reload config |
sudo systemctl restart nginx | restart service |
Reverse Proxy (Basic)
server {
listen 80;
server_name example.com;
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;
}
}
Static Files
location /assets/ {
root /var/www/app;
try_files $uri =404;
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
}
SSL / HTTPS Redirect
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
}
Gzip & Performance
gzip on;
gzip_types text/plain text/css application/json application/javascript application/xml+rss;
gzip_min_length 1024;
Security Headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "geolocation=(), microphone=()" always;
Rate Limiting
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
proxy_pass http://127.0.0.1:4000;
}
Cache Proxy
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=STATIC:10m inactive=24h max_size=1g;
location / {
proxy_cache STATIC;
proxy_cache_valid 200 10m;
proxy_pass http://127.0.0.1:3000;
}
Logs
| Path | ความหมาย |
|---|---|
/var/log/nginx/access.log | request logs |
/var/log/nginx/error.log | error logs |
Troubleshooting
| ปัญหา | วิธีเช็ก |
|---|---|
| 502 Bad Gateway | upstream app ไม่รัน / port ผิด |
| 403 Forbidden | permission/root path ไม่ถูก |
| reload ไม่ผ่าน | nginx -t ก่อน reload เสมอ |
| SSL fail | cert path / domain ไม่ตรง |