配置nginxSkill configuring-nginx

本技能提供配置 nginx 的全面指南,涵盖静态网站服务、反向代理设置、负载均衡实现、SSL/TLS 终止、缓存配置和性能优化。适用于生产环境,强调安全最佳实践,如现代 TLS 配置、速率限制和安全头部。关键词:nginx 配置, 静态网站, 反向代理, 负载均衡, SSL/TLS, 缓存, 性能调优, 安全, 服务器管理, DevOps。

DevOps 0 次安装 4 次浏览 更新于 3/23/2026

名称: 配置-nginx 描述: 配置 nginx 用于静态网站、反向代理、负载均衡、SSL/TLS 终止、缓存和性能调优。在设置 web 服务器、应用代理或负载均衡器时,本技能提供生产就绪的模式,包含现代安全最佳实践,如 TLS 1.3、速率限制和安全头部。

配置 nginx

目的

指导工程师配置 nginx 以满足常见的 web 基础设施需求:静态文件服务、反向代理后端应用、跨多个服务器的负载均衡、SSL/TLS 终止、缓存和性能优化。提供生产就绪的配置和安全最佳实践。

何时使用此技能

使用场景包括:

  • 设置静态网站或单页应用的 web 服务器
  • 为 Node.js、Python、Ruby 或 Go 应用配置反向代理
  • 在多个后端服务器上实现负载均衡
  • 为 HTTPS 流量终止 SSL/TLS
  • 添加缓存层以提高性能
  • 构建 API 网关功能
  • 通过速率限制防止 DDoS 攻击
  • 代理 WebSocket 连接

触发短语:“配置 nginx”、“nginx 反向代理”、“nginx 负载均衡器”、“在 nginx 中启用 SSL”、“nginx 性能调优”、“nginx 缓存”、“nginx 速率限制”

安装

Ubuntu/Debian:

sudo apt update && sudo apt install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx

RHEL/CentOS/Rocky:

sudo dnf install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx

Docker:

docker run -d -p 80:80 -v /path/to/config:/etc/nginx/conf.d nginx:alpine

快速开始示例

静态网站

从目录提供 HTML/CSS/JS 文件:

server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

启用站点:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

参见 references/static-sites.md 获取 SPA 配置和高级模式。

反向代理

将请求代理到后端应用服务器:

upstream app_backend {
    server 127.0.0.1:3000;
    keepalive 32;
}

server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://app_backend;
        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_http_version 1.1;
        proxy_set_header Connection "";
    }
}

参见 references/reverse-proxy.md 获取 WebSocket 代理和 API 网关模式。

SSL/TLS 配置

使用现代 TLS 配置启用 HTTPS:

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;

    ssl_protocols TLSv1.3 TLSv1.2;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:50m;
    ssl_session_timeout 1d;

    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

    location / {
        try_files $uri $uri/ =404;
    }
}

server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

参见 references/ssl-tls-config.md 获取完整的 TLS 配置和证书设置。

核心概念

配置结构

nginx 使用分层配置上下文:

nginx.conf(全局设置)
├── events { }(连接处理)
└── http { }(HTTP 级别设置)
    └── server { }(虚拟主机)
        └── location { }(URL 路由)

文件位置:

  • /etc/nginx/nginx.conf - 主配置
  • /etc/nginx/sites-available/ - 可用站点配置
  • /etc/nginx/sites-enabled/ - 已启用的站点(符号链接)
  • /etc/nginx/conf.d/*.conf - 额外配置
  • /etc/nginx/snippets/ - 可重用的配置片段

参见 references/configuration-structure.md 获取详细解剖。

位置匹配优先级

nginx 按以下顺序评估位置块:

  1. location = /exact - 精确匹配(最高优先级)
  2. location ^~ /prefix - 前缀匹配,停止搜索
  3. location ~ \.php$ - 正则表达式,区分大小写
  4. location ~* \.(jpg|png)$ - 正则表达式,不区分大小写
  5. location / - 前缀匹配(最低优先级)

示例:

location = /api/status {
    return 200 "OK
";
}

location ^~ /static/ {
    root /var/www;
}

location ~ \.php$ {
    fastcgi_pass unix:/var/run/php/php-fpm.sock;
}

location / {
    proxy_pass http://backend;
}

基本代理头部

当代理到后端时,保留客户端信息:

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;

/etc/nginx/snippets/proxy-params.conf 创建可重用片段,并使用:

include snippets/proxy-params.conf;

常见模式

负载均衡

将流量分配到多个后端服务器:

轮询(默认):

upstream backend {
    server backend1.example.com:8080;
    server backend2.example.com:8080;
    server backend3.example.com:8080;
    keepalive 32;
}

server {
    listen 80;
    location / {
        proxy_pass http://backend;
        include snippets/proxy-params.conf;
    }
}

最少连接:

upstream backend {
    least_conn;
    server backend1.example.com:8080;
    server backend2.example.com:8080;
}

IP 哈希(粘性会话):

upstream backend {
    ip_hash;
    server backend1.example.com:8080;
    server backend2.example.com:8080;
}

健康检查:

upstream backend {
    server backend1.example.com:8080 max_fails=3 fail_timeout=30s;
    server backend2.example.com:8080 max_fails=3 fail_timeout=30s;
    server backup.example.com:8080 backup;
}

参见 references/load-balancing.md 获取加权负载均衡和高级模式。

WebSocket 代理

通过升级 HTTP 协议启用 WebSocket 连接:

upstream websocket_backend {
    server 127.0.0.1:3000;
}

server {
    listen 80;
    server_name ws.example.com;

    location / {
        proxy_pass http://websocket_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;

        # 持久连接的长超时
        proxy_connect_timeout 7d;
        proxy_send_timeout 7d;
        proxy_read_timeout 7d;
    }
}

速率限制

防止滥用和 DDoS 攻击:

# 在 http 上下文中
http {
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
}

# 在 server 上下文中
server {
    listen 80;

    limit_req zone=api_limit burst=10 nodelay;
    limit_conn conn_limit 10;

    location /api/ {
        proxy_pass http://backend;
    }
}

参见 references/security-hardening.md 获取完整的安全配置。

性能优化

工作进程配置:

# 在主上下文中
user www-data;
worker_processes auto;  # 每个 CPU 核心一个
worker_rlimit_nofile 65535;

events {
    worker_connections 4096;
    use epoll;
    multi_accept on;
}

Gzip 压缩:

# 在 http 上下文中
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;

代理缓存:

# 定义缓存区域
proxy_cache_path /var/cache/nginx/proxy
                 levels=1:2
                 keys_zone=app_cache:100m
                 max_size=1g
                 inactive=60m;

# 在位置中使用
location / {
    proxy_cache app_cache;
    proxy_cache_valid 200 60m;
    proxy_cache_use_stale error timeout updating;
    add_header X-Cache-Status $upstream_cache_status;
    proxy_pass http://backend;
}

参见 references/performance-tuning.md 获取详细的优化策略。

安全头部

添加基本安全头部以防护常见漏洞:

# 创建 /etc/nginx/snippets/security-headers.conf
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" 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;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;

在 server 块中包含:

server {
    include snippets/security-headers.conf;
    # ... 其余配置
}

访问控制

通过 IP 地址限制访问:

server {
    listen 80;
    server_name admin.example.com;

    # 允许特定 IP
    allow 10.0.0.0/8;
    allow 203.0.113.0/24;

    # 拒绝所有其他
    deny all;

    location / {
        proxy_pass http://admin_backend;
    }
}

决策框架

选择 nginx 用于: 性能关键型工作负载(10K+ 连接)、反向代理、负载均衡、静态文件服务、现代应用堆栈。

选择替代方案用于: Apache(.htaccess、mod_php、遗留应用)、Caddy(自动 HTTPS、更简单配置)、Traefik(动态容器)、Envoy(服务网格)。

安全检查清单

在部署 nginx 配置之前:

  • [ ] 测试配置语法:sudo nginx -t
  • [ ] 使用重新加载,而非重启:sudo systemctl reload nginx(零停机)
  • [ ] 检查错误日志:sudo tail -f /var/log/nginx/error.log
  • [ ] 验证 SSL/TLS:openssl s_client -connect domain:443 -servername domain
  • [ ] 外部测试:curl -I https://domain.com
  • [ ] 监控工作进程:ps aux | grep nginx
  • [ ] 检查打开的连接:netstat -an | grep :80 | wc -l
  • [ ] 验证后端健康:curl -I http://localhost:8080

故障排除

快速修复: 测试配置(sudo nginx -t)、检查日志(/var/log/nginx/error.log)、验证后端(curl http://127.0.0.1:3000)。

常见错误: 502(后端下线)、504(超时 - 增加 proxy_read_timeout)、413(上传大小 - 设置 client_max_body_size)。

参见 references/troubleshooting.md 获取完整的调试指南。

集成点

相关技能:

  • implementing-tls - 证书生成和自动化(Let’s Encrypt、cert-manager)
  • load-balancing-patterns - 高级负载均衡架构和决策框架
  • deploying-applications - 应用部署策略与 nginx 集成
  • security-hardening - 超越 nginx 特定配置的完整服务器安全
  • configuring-firewalls - HTTP/HTTPS 访问的防火墙规则
  • dns-management - nginx 虚拟主机的 DNS 配置
  • kubernetes-operations - Kubernetes 的 nginx Ingress 控制器

额外资源

渐进式披露:

  • references/installation-guide.md - 所有平台的详细安装指南
  • references/configuration-structure.md - 完整的 nginx.conf 解剖
  • references/static-sites.md - 静态托管模式(基础、SPA、PHP)
  • references/reverse-proxy.md - 高级代理场景和 API 网关模式
  • references/load-balancing.md - 所有算法、健康检查、粘性会话
  • references/ssl-tls-config.md - 完整的 TLS 配置和证书设置
  • references/performance-tuning.md - 工作进程、缓存、压缩、缓冲区
  • references/security-hardening.md - 速率限制、头部、访问控制
  • references/troubleshooting.md - 常见错误和调试技术

工作示例:

  • examples/static-site/ - 静态网站和 SPA 配置
  • examples/reverse-proxy/ - Node.js、WebSocket、API 网关示例
  • examples/load-balancing/ - 所有负载均衡算法
  • examples/ssl-tls/ - 现代 TLS 和 mTLS 配置
  • examples/performance/ - 高流量优化和缓存
  • examples/security/ - 速率限制和安全加固

可重用片段:

  • snippets/ssl-modern.conf - 现代 TLS 配置
  • snippets/proxy-params.conf - 标准代理头部
  • snippets/security-headers.conf - OWASP 安全头部
  • snippets/cache-static.conf - 静态资源缓存