mcpField
C
configuring-nginx

configuring-nginx

github.com/ancoleman云与 DevOps52581 次安装46 周前更新
代码仓库

关于 configuring-nginx

面向工程师的 nginx 配置指南,提供静态站点、反向代理、负载均衡、TLS、缓存和安全配置模式,并配有示例与排错资料。

主要功能

  1. 01静态站点与 SPA 托管
  2. 02反向代理和 API 网关配置
  3. 03负载均衡与健康检查
  4. 04TLS、缓存和性能调优
  5. 05限流、访问控制与安全头

适用场景

  1. 01为应用配置 HTTPS 反向代理
  2. 02在多个后端间分配流量
  3. 03部署静态站点或 SPA
  4. 04为 API 添加限流与缓存

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/ancoleman/ai-design-components --skill configuring-nginx

安装后在 Claude Code 中输入/configuring-nginx确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

outputs.yaml
examples/load-balancing/
round-robin.conf
examples/reverse-proxy/
nodejs-app.conf
websocket.conf
examples/static-site/
basic.conf
spa.conf
references/
configuration-structure.md
installation-guide.md
load-balancing.md
performance-tuning.md
reverse-proxy.md
security-hardening.md
ssl-tls-config.md
static-sites.md
troubleshooting.md
snippets/
cache-static.conf
proxy-params.conf
security-headers.conf
ssl-modern.conf

详细介绍

配置 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

SPA 配置和高级模式请参阅 references/static-sites.md。

反向代理

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

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 "";
    }
}

WebSocket 代理和 API 网关模式请参阅 references/reverse-proxy.md。

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;
}

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

核心概念

配置结构

nginx 使用分层配置上下文:

nginx.conf (global settings)
├── events { } (connection processing)
└── http { } (HTTP-level settings)
    └── server { } (virtual host)
        └── location { } (URL routing)

文件位置:

  • /etc/nginx/nginx.conf - 主配置文件
  • /etc/nginx/sites-available/ - 可用站点配置
  • /etc/nginx/sites-enabled/ - 已启用的站点(符号链接)
  • /etc/nginx/conf.d/*.conf - 其他配置
  • /etc/nginx/snippets/ - 可复用的配置片段

详细结构请参阅 references/configuration-structure.md。

Location 匹配优先级

nginx 按以下顺序评估 location 块:

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

示例:

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

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;

        # Long timeouts for persistent connections
        proxy_connect_timeout 7d;
        proxy_send_timeout 7d;
        proxy_read_timeout 7d;
    }
}
速率限制

防范滥用和 DDoS 攻击:

# In http context
http {
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
}

# In server context
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。

性能优化

工作进程配置:

# In main context
user www-data;
worker_processes auto;  # 1 per CPU core
worker_rlimit_nofile 65535;

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

Gzip 压缩:

# In http context
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;

代理缓存:

# Define cache zone
proxy_cache_path /var/cache/nginx/proxy
                 levels=1:2
                 keys_zone=app_cache:100m
                 max_size=1g
                 inactive=60m;

# Use in location
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。

安全标头

添加必要的安全标头,以防范常见漏洞:

# Create /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;
    # ... rest of config
}
访问控制

按 IP 地址限制访问:

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

    # Allow specific IPs
    allow 10.0.0.0/8;
    allow 203.0.113.0/24;

    # Deny all others
    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 Controller

更多资源

渐进式披露:

  • 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 - 静态资源缓存

评论

支持 Markdown