系统系统Nginx配置
野菜Nginx 详细配置手册
目录
- Nginx 安装和基本配置
- 核心配置详解
- 虚拟主机配置
- 负载均衡配置
- 反向代理配置
- HTTPS 和 SSL 配置
- 缓存和性能优化
- 安全配置
- 日志配置
- 常见问题排查
Nginx 安装和基本配置
1. 安装 Nginx
CentOS/RHEL:
1 2 3 4 5 6 7 8 9
| yum install -y epel-release
yum install -y nginx
systemctl enable nginx systemctl start nginx
|
Ubuntu/Debian:
1 2 3 4 5 6 7 8 9
| apt update
apt install -y nginx
systemctl enable nginx systemctl start nginx
|
编译安装(最新版本):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| yum groupinstall -y "Development Tools" yum install -y pcre-devel zlib-devel openssl-devel
wget http://nginx.org/download/nginx-1.24.0.tar.gz tar zxvf nginx-1.24.0.tar.gz cd nginx-1.24.0
./configure --prefix=/usr/local/nginx \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_stub_status_module \ --with-http_gzip_static_module \ --with-http_realip_module
make && make install
|
2. 目录结构
1 2 3 4 5 6 7 8 9 10
| /etc/nginx/ ├── nginx.conf # 主配置文件 ├── conf.d/ # 额外配置文件目录 ├── sites-available/ # 可用的站点配置 ├── sites-enabled/ # 已启用的站点配置 ├── modules/ # 模块目录 └── ssl/ # SSL证书目录
/var/log/nginx/ # 日志目录 /usr/share/nginx/html/ # 默认网站根目录
|
3. 基本操作命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| nginx -t
nginx -s reload
nginx -s stop
nginx -s quit
nginx -V
systemctl status nginx systemctl restart nginx systemctl reload nginx
|
核心配置详解
1. 主配置文件结构 (nginx.conf)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| user nginx nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events { worker_connections 1024; use epoll; multi_accept on; }
http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; gzip on; gzip_vary on; gzip_min_length 1024; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; }
|
虚拟主机配置
1. 基本虚拟主机配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| server { listen 80; server_name example.com www.example.com; root /var/www/example.com; index index.html index.htm index.php; charset utf-8; access_log /var/log/nginx/example.com.access.log; error_log /var/log/nginx/example.com.error.log; location / { try_files $uri $uri/ =404; } location ~ /\. { deny all; access_log off; log_not_found off; } }
|
2. PHP 应用配置(WordPress等)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| server { listen 80; server_name phpapp.com; root /var/www/phpapp; index index.php index.html index.htm; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; fastcgi_param HTTP_PROXY ""; fastcgi_intercept_errors off; fastcgi_buffer_size 16k; fastcgi_buffers 4 16k; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; } location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 1y; add_header Cache-Control "public, immutable"; } }
|
3. Node.js 应用反向代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| server { listen 80; server_name nodeapp.com; location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; 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_cache_bypass $http_upgrade; proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; } }
|
4. Python Django/Flask 应用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| server { listen 80; server_name pythonapp.com; location /static/ { alias /var/www/pythonapp/static/; expires 30d; add_header Cache-Control "public"; } location /media/ { alias /var/www/pythonapp/media/; expires 30d; add_header Cache-Control "public"; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $http_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_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }
|
负载均衡配置
1. 基本负载均衡
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| upstream backend_servers { server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; }
server { listen 80; server_name loadbalance.com; location / { proxy_pass http://backend_servers; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
|
2. 高级负载均衡策略
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| upstream backend_servers { server 192.168.1.10:8080 weight=3; server 192.168.1.11:8080 weight=2; server 192.168.1.12:8080 weight=1; least_conn; server 192.168.1.13:8080 backup; }
upstream app_servers { ip_hash; server 192.168.1.20:8080; server 192.168.1.21:8080; server 192.168.1.22:8080; }
upstream geo_servers { hash $remote_addr consistent; server 192.168.1.30:8080; server 192.168.1.31:8080; }
|
3. 健康检查配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| 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; check interval=3000 rise=2 fall=5 timeout=1000 type=http; check_http_send "HEAD /health HTTP/1.0\r\n\r\n"; check_http_expect_alive http_2xx http_3xx; }
server { location /nginx_status { check_status; access_log off; allow 192.168.1.0/24; deny all; } }
|
反向代理配置
1. 基本反向代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| server { listen 80; server_name proxy.com; location /app/ { rewrite ^/app/(.*) /$1 break; proxy_pass http://backend_server; 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_buffering on; proxy_buffer_size 4k; proxy_buffers 8 4k; proxy_connect_timeout 30s; proxy_send_timeout 30s; proxy_read_timeout 30s; } }
|
2. 高级代理配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| location /api/ { proxy_pass http://api_backend; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_http_version 1.1; proxy_buffers 16 32k; proxy_buffer_size 64k; proxy_busy_buffers_size 64k; proxy_connect_timeout 5s; proxy_send_timeout 60s; proxy_read_timeout 60s; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; proxy_next_upstream_tries 3; proxy_next_upstream_timeout 10s; }
|
HTTPS 和 SSL 配置
1. 基本 HTTPS 配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| server { listen 443 ssl http2; server_name example.com; ssl_certificate /etc/nginx/ssl/example.com.crt; ssl_certificate_key /etc/nginx/ssl/example.com.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384; ssl_prefer_server_ciphers off; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; add_header Strict-Transport-Security "max-age=63072000" always; add_header X-Frame-Options DENY; add_header X-Content-Type-Options nosniff; root /var/www/example.com; index index.html; }
|
2. HTTP 重定向到 HTTPS
1 2 3 4 5
| server { listen 80; server_name example.com www.example.com; return 301 https://$server_name$request_uri; }
|
3. 免费 SSL (Let’s Encrypt)
1 2 3 4 5 6 7 8 9 10 11
| yum install -y certbot python3-certbot-nginx
certbot --nginx -d example.com -d www.example.com
certbot renew --dry-run
echo "0 0,12 * * * root python3 -c 'import random; import time; time.sleep(random.random() * 3600)' && certbot renew -q" | sudo tee -a /etc/crontab > /dev/null
|
缓存和性能优化
1. 代理缓存配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
server { location / { proxy_cache my_cache; proxy_cache_key "$scheme$request_method$host$request_uri"; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; proxy_cache_background_update on; proxy_cache_lock on; add_header X-Cache-Status $upstream_cache_status; proxy_pass http://backend; } }
|
2. 静态文件缓存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| server { location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ { expires 1y; add_header Cache-Control "public, immutable"; add_header Vary Accept-Encoding; try_files $uri =404; } location ~* \.(html|htm)$ { expires 1h; add_header Cache-Control "public"; } }
|
3. Gzip 压缩优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| gzip on; gzip_vary on; gzip_min_length 1024; gzip_proxied any; gzip_comp_level 6; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/atom+xml image/svg+xml;
|
安全配置
1. 基本安全设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| server { server_tokens off; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-XSS-Protection "1; mode=block" always; add_header X-Content-Type-Options "nosniff" always; add_header Referrer-Policy "no-referrer-when-downgrade" always; add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always; client_max_body_size 10m; add_header X-Frame-Options DENY; }
|
2. 访问控制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| location /admin/ { allow 192.168.1.0/24; allow 10.0.0.1; deny all; auth_basic "Administrator's Area"; auth_basic_user_file /etc/nginx/.htpasswd; }
location ~ /\.ht { deny all; }
location /api/ { limit_except GET POST { deny all; } }
|
3. 速率限制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; limit_req_zone $binary_remote_addr zone=login:10m rate=1r/m;
server { location /api/ { limit_req zone=api burst=20 nodelay; proxy_pass http://api_backend; } location /login { limit_req zone=login burst=5; proxy_pass http://auth_backend; } }
|
日志配置
1. 自定义日志格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" ' 'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"'; log_format json_analytics escape=json '{' '"time_local":"$time_local",' '"remote_addr":"$remote_addr",' '"remote_user":"$remote_user",' '"request":"$request",' '"status": "$status",' '"body_bytes_sent":"$body_bytes_sent",' '"request_time":$request_time,' '"http_referer":"$http_referer",' '"http_user_agent":"$http_user_agent",' '"http_x_forwarded_for":"$http_x_forwarded_for"' '}'; access_log /var/log/nginx/access.log main; }
|
2. 日志分割和管理
1 2 3 4 5 6 7 8 9 10 11 12
| #!/bin/bash
mv /var/log/nginx/access.log /var/log/nginx/access_$(date +%Y%m%d).log mv /var/log/nginx/error.log /var/log/nginx/error_$(date +%Y%m%d).log
kill -USR1 $(cat /var/run/nginx.pid)
find /var/log/nginx/ -name "*.log" -mtime +30 -delete
|
常见问题排查
1. 配置检查
1 2 3 4 5 6 7 8
| nginx -t
nginx -t -c /etc/nginx/nginx.conf
nginx -T
|
2. 日志分析
1 2 3 4 5 6 7 8 9 10 11
| tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
awk '{print $9}' access.log | sort | uniq -c | sort -rn
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -20
|
3. 性能监控
1 2 3 4 5 6 7 8 9 10 11 12
| server { listen 8080; server_name 127.0.0.1; location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } }
|
4. 常见错误解决
502 Bad Gateway
1 2 3 4 5 6 7 8 9 10 11 12
| location / { proxy_pass http://backend; proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; proxy_buffers 8 16k; proxy_buffer_size 32k; }
|
413 Request Entity Too Large
1 2 3 4 5 6 7
| server { client_max_body_size 100M; location /upload { client_max_body_size 500M; } }
|
这份 Nginx 配置手册涵盖了从基础到高级的各种配置场景,可以根据实际需求选择相应的配置片段进行使用。记得在修改配置后使用 nginx -t 测试语法,然后重新加载配置。