Nginx 实战配置示例

Nginx 实战配置示例

ℹ️生产环境常用 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
# /etc/nginx/sites-available/static-website.conf
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
# HTTP 重定向到 HTTPS
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;

# Let's Encrypt 验证路径
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}

# 其他请求重定向到 HTTPS
location / {
return 301 https://$server_name$request_uri;
}
}

# HTTPS 配置
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com www.example.com;

# SSL 证书配置
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;

# WebSocket 支持
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;
}

# 静态文件直接由 Nginx 处理
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
# /etc/nginx/snippets/ssl-params.conf

# SSL 协议配置
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 会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;

# OCSP Stapling
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
# /etc/nginx/snippets/proxy-params.conf

# 基础代理头
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;

# HTTP 版本
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;
}

# API 请求代理
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
# HTTP 重定向
server {
listen 80;
server_name blog.example.com;
return 301 https://$server_name$request_uri;
}

# HTTPS 配置
server {
listen 443 ssl http2;
server_name blog.example.com;

root /var/www/html;
index index.php index.html index.htm;

# SSL 配置
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;

# WordPress 标准配置
location / {
try_files $uri $uri/ /index.php?$args;
}

# PHP 处理
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
}

# WordPress 管理后台限制
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
# Docker 服务网格配置
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;

# Docker 特殊配置
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_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
# Nginx 状态页面
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
# nginx_log_analyzer.sh

# 分析访问最多的 IP
echo "Top 10 IPs:"
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10

# 分析访问最多的 URL
echo -e "\nTop 10 URLs:"
awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10

# 分析 HTTP 状态码
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
# 使用 git 管理配置文件
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

# 或者使用 systemctl
sudo systemctl reload nginx

🔗 相关资源

学习资源


💡 实践建议

[success] 部署建议

  1. 开发环境先充分测试
  2. 使用版本控制管理配置
  3. 建立配置备份机制
  4. 设置监控和告警
  5. 定期更新和安全检查
  6. 准备应急处理预案

📚 学习路径总结

恭喜你完成了 Nginx 学习笔记的全套内容!现在你已经掌握:

  1. 基础入门01_Nginx入门指南_基础概念
  2. 反向代理与负载均衡02_Nginx反向代理与负载均衡_实战教程
  3. 性能优化与安全配置03_Nginx性能优化与安全配置_最佳实践
  4. 实战配置04_Nginx实战配置示例_项目部署

下一步建议:

  • 在测试环境搭建完整的 Nginx 服务
  • 尝试部署实际项目
  • 学习更多高级功能和调优技巧
  • 关注 Nginx 社区最新动态

祝你学习愉快!🎉