nginx
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseNginx Configuration and Optimization
Nginx配置与优化
Overview
概述
Nginx web server configuration, reverse proxy, load balancing, performance optimization and other skills.
Nginx Web服务器配置、反向代理、负载均衡、性能优化等相关技巧。
Basic Management
基础管理
Service Control
服务控制
bash
undefinedbash
undefinedStart/Stop services
启动/停止服务
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl reload nginx # Graceful reload config
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
systemctl reload nginx # 平滑重载配置
Configuration test
配置测试
nginx -t
nginx -T # Test and print config
undefinednginx -t
nginx -T # 测试并打印配置
undefinedConfiguration Files
配置文件
bash
undefinedbash
undefinedMain configuration file
主配置文件
/etc/nginx/nginx.conf
/etc/nginx/nginx.conf
Site configuration
站点配置
/etc/nginx/conf.d/*.conf
/etc/nginx/sites-available/
/etc/nginx/sites-enabled/
/etc/nginx/conf.d/*.conf
/etc/nginx/sites-available/
/etc/nginx/sites-enabled/
Log files
日志文件
/var/log/nginx/access.log
/var/log/nginx/error.log
undefined/var/log/nginx/access.log
/var/log/nginx/error.log
undefinedBasic Configuration
基础配置
Static Website
静态网站
nginx
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# Static resource caching
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
}nginx
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
}HTTPS Configuration
HTTPS配置
nginx
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
# SSL optimization
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
# HSTS
add_header Strict-Transport-Security "max-age=31536000" always;
}nginx
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
# SSL优化
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
# HSTS
add_header Strict-Transport-Security "max-age=31536000" always;
}HTTP redirect to HTTPS
HTTP重定向到HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
undefinedserver {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
undefinedReverse Proxy
反向代理
Basic Proxy
基础代理
nginx
server {
listen 80;
server_name api.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;
}
}nginx
server {
listen 80;
server_name api.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;
}
}WebSocket Proxy
WebSocket代理
nginx
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";
proxy_set_header Host $host;
proxy_read_timeout 86400;
}nginx
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";
proxy_set_header Host $host;
proxy_read_timeout 86400;
}Load Balancing
负载均衡
Basic Configuration
基础配置
nginx
upstream backend {
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=2;
server 192.168.1.12:8080 backup;
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_next_upstream error timeout http_500;
}
}nginx
upstream backend {
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=2;
server 192.168.1.12:8080 backup;
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_next_upstream error timeout http_500;
}
}Load Balancing Strategies
负载均衡策略
nginx
undefinednginx
undefinedRound Robin (default)
轮询(默认)
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
IP Hash (session persistence)
IP哈希(会话保持)
upstream backend {
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
upstream backend {
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
Least Connections
最少连接数
upstream backend {
least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
upstream backend {
least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
Health Check
健康检查
upstream backend {
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
}
undefinedupstream backend {
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
}
undefinedPerformance Optimization
性能优化
Basic Optimization
基础优化
nginx
undefinednginx
undefinednginx.conf
nginx.conf
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 65535;
use epoll;
multi_accept on;
}
http {
# File transfer optimization
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# Timeout settings
keepalive_timeout 65;
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;
# Buffer settings
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 32k;}
undefinedworker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 65535;
use epoll;
multi_accept on;
}
http {
# 文件传输优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 超时设置
keepalive_timeout 65;
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;
# 缓冲区设置
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 32k;}
undefinedGzip Compression
Gzip压缩
nginx
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml;nginx
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml;Common Scenarios
常见场景
Scenario 1: PHP-FPM Configuration
场景1:PHP-FPM配置
nginx
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}nginx
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}Scenario 2: Rate Limiting
场景2:请求限流
nginx
undefinednginx
undefinedDefine rate limit zone
定义限流区域
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server {
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
}
}
undefinedlimit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
server {
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
}
}
undefinedScenario 3: Access Control
场景3:访问控制
nginx
location /admin {
allow 192.168.1.0/24;
deny all;
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}nginx
location /admin {
allow 192.168.1.0/24;
deny all;
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}Troubleshooting
故障排查
| Problem | Solution |
|---|---|
| Configuration error | |
| 502 Bad Gateway | Check backend service, upstream config |
| 504 Gateway Timeout | Increase proxy_read_timeout |
| Permission issues | Check file permissions, SELinux |
| Performance issues | Check worker_connections, log analysis |
| 问题 | 解决方案 |
|---|---|
| 配置错误 | 使用 |
| 502 Bad Gateway | 检查后端服务、上游配置 |
| 504 Gateway Timeout | 增大proxy_read_timeout值 |
| 权限问题 | 检查文件权限、SELinux设置 |
| 性能问题 | 检查worker_connections、分析日志 |