Nginx 实战配置示例
🎯 学习目标
- 掌握常见业务场景的 Nginx 配置
- 学习生产环境的最佳实践
- 了解微服务架构的 Nginx 部署
- 实战:完整的项目部署配置
📋 目录结构
推荐的配置文件组织
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| /etc/nginx/ ├── nginx.conf # 主配置文件 ├── conf.d/ │ ├── upstream.conf # 后端服务器组配置 │ ├── ssl.conf # SSL配置 │ └── security.conf # 安全配置 ├── sites-available/ # 可用站点 │ ├── website1.conf │ ├── website2.conf │ └── api.conf ├── sites-enabled/ # 已启用站点(软链接) └── snippets/ # 配置片段 ├── ssl-params.conf ├── proxy-params.conf └── wp-common.conf
|
🚀 实战场景配置
场景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 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| server { listen 80; listen [::]:80;
server_name example.com www.example.com; root /var/www/example.com; index index.html index.htm;
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 ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ { expires 365d; add_header Cache-Control "public, immutable"; access_log off; }
location ~ /\. { deny all; access_log off; log_not_found off; }
add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; }
|
场景2: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 26 27 28 29 30 31 32 33 34 35 36
| server { listen 80; listen [::]:80; server_name example.com www.example.com;
location /.well-known/acme-challenge/ { root /var/www/certbot; }
location / { return 301 https://$server_name$request_uri; } }
server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; include /etc/nginx/snippets/ssl-params.conf;
root /var/www/example.com; index index.html;
location / { try_files $uri $uri/ =404; } }
|
场景3:反向代理 Node.js 应用
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
| upstream nodejs_backend { server 127.0.0.1:3000; keepalive 64; }
server { listen 80; server_name api.example.com;
access_log /var/log/nginx/api.access.log; error_log /var/log/nginx/api.error.log;
location / { proxy_pass http://nodejs_backend; include /etc/nginx/snippets/proxy-params.conf;
proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";
proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; }
location /static { alias /var/www/nodejs-app/public; expires 30d; add_header Cache-Control "public"; }
location /health { access_log off; return 200 "healthy\n"; add_header Content-Type text/plain; } }
|
场景4:微服务架构网关
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
| upstream user_service { least_conn; server user1.example.com:8001 weight=2; server user2.example.com:8001 weight=1; keepalive 32; }
upstream order_service { ip_hash; server order1.example.com:8002; server order2.example.com:8002; keepalive 32; }
upstream payment_service { server payment1.example.com:8003 backup; server payment2.example.com:8003; keepalive 32; }
upstream frontend_service { server frontend1.example.com:3000; server frontend2.example.com:3000; }
server { listen 80; server_name api.example.com;
location /api/users { proxy_pass http://user_service; include /etc/nginx/snippets/proxy-params.conf; }
location /api/orders { proxy_pass http://order_service; include /etc/nginx/snippets/proxy-params.conf; }
location /api/payment { proxy_pass http://payment_service; include /etc/nginx/snippets/proxy-params.conf; }
location / { proxy_pass http://frontend_service; include /etc/nginx/snippets/proxy-params.conf; } }
|
🛠️ 配置片段模板
SSL 参数配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384'; ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_session_tickets off;
ssl_stapling on; ssl_stapling_verify on;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always;
|
代理参数配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
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_set_header X-Forwarded-Host $http_host;
proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s;
proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 4k; proxy_busy_buffers_size 8k;
proxy_http_version 1.1; proxy_set_header Connection "";
|
📱 实战项目案例
案例1:Vue.js 单页应用部署
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
| server { listen 80; server_name spa.example.com;
root /var/www/vue-spa; index index.html;
location / { try_files $uri $uri/ /index.html; }
location /api { proxy_pass http://backend-api:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }
location /js { expires 1y; add_header Cache-Control "public, immutable"; }
location /css { expires 1y; add_header Cache-Control "public, immutable"; }
location /images { expires 1y; add_header Cache-Control "public, immutable"; } }
|
案例2: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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| server { listen 80; server_name blog.example.com; return 301 https://$server_name$request_uri; }
server { listen 443 ssl http2; server_name blog.example.com;
root /var/www/html; index index.php index.html index.htm;
ssl_certificate /etc/letsencrypt/live/blog.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/blog.example.com/privkey.pem; include /etc/nginx/snippets/ssl-params.conf;
access_log /var/log/nginx/blog.access.log; error_log /var/log/nginx/blog.error.log;
location / { try_files $uri $uri/ /index.php?$args; }
location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; }
location ~* wp-admin { allow 192.168.1.0/24; deny all; }
location ~* /(?:\.htaccess|\.htpasswd|\.git|\.svn|wp-config\.php) { deny all; }
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2)$ { expires 365d; add_header Cache-Control "public, immutable"; } }
|
案例3:Docker 容器服务代理
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
| upstream docker_services { server docker1:8080; server docker2:8080; server docker3:8080; }
server { listen 80; server_name docker.example.com;
location /health { proxy_pass http://docker_services/health; access_log off; }
location / { proxy_pass http://docker_services; include /etc/nginx/snippets/proxy-params.conf;
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"; }
location /metrics { proxy_pass http://docker_services/metrics; allow 127.0.0.1; allow 192.168.1.0/24; deny all; } }
|
🔧 监控和运维
状态监控配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| server { listen 80; server_name status.example.com;
location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; allow 192.168.1.0/24; deny all; }
location /server_info { default_type text/plain; return 200 "Server: $hostname\nTime: $time_local\n"; } }
|
日志分析脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #!/bin/bash
echo "Top 10 IPs:" awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10
echo -e "\nTop 10 URLs:" awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10
echo -e "\nHTTP Status Codes:" awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -nr
|
🚨 故障排查
常见问题解决
1. 502 Bad Gateway
1 2 3 4 5 6 7 8 9 10
| proxy_connect_timeout 300; proxy_send_timeout 300; proxy_read_timeout 300;
upstream backend { server backend1:8080 max_fails=3 fail_timeout=30s; server backend2:8080 max_fails=3 fail_timeout=30s; }
|
2. 413 Request Entity Too Large
1 2 3
| client_max_body_size 50M; client_body_buffer_size 128k;
|
3. 504 Gateway Timeout
1 2 3 4 5
| proxy_connect_timeout 600; proxy_send_timeout 600; proxy_read_timeout 600; send_timeout 600;
|
📝 配置管理最佳实践
1. 版本控制
1 2 3 4 5 6 7 8
| cd /etc/nginx sudo git init sudo git add . sudo git commit -m "Initial nginx configuration"
sudo cp nginx.conf nginx.conf.backup
|
2. 配置测试
1 2 3 4 5
| sudo nginx -t
sudo nginx -t -c /etc/nginx/sites-available/mysite.conf
|
3. 平滑重载
1 2 3 4 5
| sudo nginx -s reload
sudo systemctl reload nginx
|
🔗 相关资源
学习资源
💡 实践建议
[success] 部署建议
- 开发环境先充分测试
- 使用版本控制管理配置
- 建立配置备份机制
- 设置监控和告警
- 定期更新和安全检查
- 准备应急处理预案
📚 学习路径总结
恭喜你完成了 Nginx 学习笔记的全套内容!现在你已经掌握:
- ✅ 基础入门:01_Nginx入门指南_基础概念
- ✅ 反向代理与负载均衡:02_Nginx反向代理与负载均衡_实战教程
- ✅ 性能优化与安全配置:03_Nginx性能优化与安全配置_最佳实践
- ✅ 实战配置:04_Nginx实战配置示例_项目部署
下一步建议:
- 在测试环境搭建完整的 Nginx 服务
- 尝试部署实际项目
- 学习更多高级功能和调优技巧
- 关注 Nginx 社区最新动态
祝你学习愉快!🎉