configuring-nginx

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Configuring nginx

配置Nginx

Purpose

目的

Guide engineers through configuring nginx for common web infrastructure needs: static file serving, reverse proxying backend applications, load balancing across multiple servers, SSL/TLS termination, caching, and performance optimization. Provides production-ready configurations with security best practices.
指导工程师针对常见Web基础设施需求配置Nginx:静态文件托管、后端应用反向代理、多服务器负载均衡、SSL/TLS终止、缓存及性能优化。提供遵循安全最佳实践的可直接用于生产环境的配置方案。

When to Use This Skill

适用场景

Use when working with:
  • Setting up web server for static sites or single-page applications
  • Configuring reverse proxy for Node.js, Python, Ruby, or Go applications
  • Implementing load balancing across multiple backend servers
  • Terminating SSL/TLS for HTTPS traffic
  • Adding caching layer for performance improvement
  • Building API gateway functionality
  • Protecting against DDoS with rate limiting
  • Proxying WebSocket connections
Trigger phrases: "configure nginx", "nginx reverse proxy", "nginx load balancer", "enable SSL in nginx", "nginx performance tuning", "nginx caching", "nginx rate limiting"
适用于以下场景:
  • 为静态站点或单页应用搭建Web服务器
  • 为Node.js、Python、Ruby或Go应用配置反向代理
  • 在多台后端服务器间实现负载均衡
  • 为HTTPS流量处理SSL/TLS终止
  • 添加缓存层以提升性能
  • 构建API网关功能
  • 通过速率限制防护DDoS攻击
  • 代理WebSocket连接
触发关键词:配置Nginx、Nginx反向代理、Nginx负载均衡器、在Nginx中启用SSL、Nginx性能调优、Nginx缓存、Nginx速率限制

Installation

安装

Ubuntu/Debian:
bash
sudo apt update && sudo apt install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx
RHEL/CentOS/Rocky:
bash
sudo dnf install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx
Docker:
bash
docker run -d -p 80:80 -v /path/to/config:/etc/nginx/conf.d nginx:alpine
Ubuntu/Debian系统:
bash
sudo apt update && sudo apt install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx
RHEL/CentOS/Rocky系统:
bash
sudo dnf install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx
Docker部署:
bash
docker run -d -p 80:80 -v /path/to/config:/etc/nginx/conf.d nginx:alpine

Quick Start Examples

快速入门示例

Static Website

静态网站

Serve HTML/CSS/JS files from a directory:
nginx
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";
    }
}
Enable site:
bash
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
See
references/static-sites.md
for SPA configurations and advanced patterns.
从指定目录托管HTML/CSS/JS文件:
nginx
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";
    }
}
启用站点:
bash
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
如需单页应用配置及进阶方案,请参考
references/static-sites.md

Reverse Proxy

反向代理

Proxy requests to a backend application server:
nginx
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 "";
    }
}
See
references/reverse-proxy.md
for WebSocket proxying and API gateway patterns.
将请求代理至后端应用服务器:
nginx
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 Configuration

SSL/TLS配置

Enable HTTPS with modern TLS configuration:
nginx
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;
}
See
references/ssl-tls-config.md
for complete TLS configuration and certificate setup.
通过现代TLS配置启用HTTPS:
nginx
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

Core Concepts

核心概念

Configuration Structure

配置结构

nginx uses hierarchical configuration contexts:
nginx.conf (global settings)
├── events { } (connection processing)
└── http { } (HTTP-level settings)
    └── server { } (virtual host)
        └── location { } (URL routing)
File locations:
  • /etc/nginx/nginx.conf
    - Main configuration
  • /etc/nginx/sites-available/
    - Available site configs
  • /etc/nginx/sites-enabled/
    - Enabled sites (symlinks)
  • /etc/nginx/conf.d/*.conf
    - Additional configs
  • /etc/nginx/snippets/
    - Reusable config snippets
See
references/configuration-structure.md
for detailed anatomy.
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

Location Matching Priority

位置匹配优先级

nginx evaluates location blocks in this order:
  1. location = /exact
    - Exact match (highest priority)
  2. location ^~ /prefix
    - Prefix match, stop searching
  3. location ~ \.php$
    - Regex, case-sensitive
  4. location ~* \.(jpg|png)$
    - Regex, case-insensitive
  5. location /
    - Prefix match (lowest priority)
Example:
nginx
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;
}
Nginx按以下顺序匹配location块:
  1. location = /exact
    - 精确匹配(优先级最高)
  2. location ^~ /prefix
    - 前缀匹配,匹配后停止搜索
  3. location ~ \.php$
    - 正则匹配,区分大小写
  4. location ~* \.(jpg|png)$
    - 正则匹配,不区分大小写
  5. location /
    - 前缀匹配(优先级最低)
示例:
nginx
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;
}

Essential Proxy Headers

必备代理标头

When proxying to backends, preserve client information:
nginx
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;
Create reusable snippet at
/etc/nginx/snippets/proxy-params.conf
and include with:
nginx
include snippets/proxy-params.conf;
代理至后端服务器时,需保留客户端信息:
nginx
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
,并通过以下方式引入:
nginx
include snippets/proxy-params.conf;

Common Patterns

常见配置方案

Load Balancing

负载均衡

Distribute traffic across multiple backend servers:
Round Robin (default):
nginx
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;
    }
}
Least Connections:
nginx
upstream backend {
    least_conn;
    server backend1.example.com:8080;
    server backend2.example.com:8080;
}
IP Hash (sticky sessions):
nginx
upstream backend {
    ip_hash;
    server backend1.example.com:8080;
    server backend2.example.com:8080;
}
Health Checks:
nginx
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;
}
See
references/load-balancing.md
for weighted load balancing and advanced patterns.
在多台后端服务器间分发流量:
轮询(默认):
nginx
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;
    }
}
最少连接数:
nginx
upstream backend {
    least_conn;
    server backend1.example.com:8080;
    server backend2.example.com:8080;
}
IP哈希(会话保持):
nginx
upstream backend {
    ip_hash;
    server backend1.example.com:8080;
    server backend2.example.com:8080;
}
健康检查:
nginx
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 Proxying

WebSocket代理

Enable WebSocket connections by upgrading HTTP protocol:
nginx
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;
    }
}
通过升级HTTP协议启用WebSocket连接:
nginx
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;
    }
}

Rate Limiting

速率限制

Protect against abuse and DDoS attacks:
nginx
undefined
防护滥用及DDoS攻击:
nginx
undefined

In http context

在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; }
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上下文配置

server { listen 80;
limit_req zone=api_limit burst=10 nodelay;
limit_conn conn_limit 10;

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

See `references/security-hardening.md` for complete security configuration.
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`。

Performance Optimization

性能优化

Worker Configuration:
nginx
undefined
工作进程配置:
nginx
undefined

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 Compression:**
```nginx
user www-data; worker_processes auto; # 每个CPU核心对应一个进程 worker_rlimit_nofile 65535;
events { worker_connections 4096; use epoll; multi_accept on; }

**Gzip压缩:**
```nginx

In http context

在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 Caching:**
```nginx
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;

**代理缓存:**
```nginx

Define cache zone

定义缓存区域

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

Use in location

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

See `references/performance-tuning.md` for detailed optimization strategies.
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`。

Security Headers

安全标头

Add essential security headers to protect against common vulnerabilities:
nginx
undefined
添加必要的安全标头以防护常见漏洞:
nginx
undefined

Create /etc/nginx/snippets/security-headers.conf

创建/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;

Include in server blocks:
```nginx
server {
    include snippets/security-headers.conf;
    # ... rest of config
}
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块中引入该片段:
```nginx
server {
    include snippets/security-headers.conf;
    # ... 其余配置
}

Access Control

访问控制

Restrict access by IP address:
nginx
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;
    }
}
通过IP地址限制访问:
nginx
server {
    listen 80;
    server_name admin.example.com;

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

    # 拒绝其余所有IP
    deny all;

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

Decision Framework

决策框架

Choose nginx for: Performance-critical workloads (10K+ connections), reverse proxy, load balancing, static file serving, modern application stacks.
Choose alternatives for: Apache (
.htaccess
, mod_php, legacy apps), Caddy (auto-HTTPS, simpler config), Traefik (dynamic containers), Envoy (service mesh).
选择Nginx的场景: 对性能要求严苛的工作负载(支持10000+并发连接)、反向代理、负载均衡、静态文件托管、现代应用栈。
选择替代方案的场景: Apache(需要
.htaccess
、mod_php或遗留应用)、Caddy(自动HTTPS、配置更简洁)、Traefik(动态容器场景)、Envoy(服务网格)。

Safety Checklist

安全检查清单

Before deploying nginx configurations:
  • Test configuration syntax:
    sudo nginx -t
  • Use reload, not restart:
    sudo systemctl reload nginx
    (zero downtime)
  • Check error logs:
    sudo tail -f /var/log/nginx/error.log
  • Verify SSL/TLS:
    openssl s_client -connect domain:443 -servername domain
  • Test externally:
    curl -I https://domain.com
  • Monitor worker processes:
    ps aux | grep nginx
  • Check open connections:
    netstat -an | grep :80 | wc -l
  • Verify backend health:
    curl -I http://localhost:8080
部署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

Troubleshooting

故障排除

Quick fixes: Test config (
sudo nginx -t
), check logs (
/var/log/nginx/error.log
), verify backend (
curl http://127.0.0.1:3000
).
Common errors: 502 (backend down), 504 (timeout - increase
proxy_read_timeout
), 413 (upload size - set
client_max_body_size
).
See
references/troubleshooting.md
for complete debugging guide.
快速修复步骤: 测试配置(
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

Integration Points

集成要点

Related Skills:
  • implementing-tls - Certificate generation and automation (Let's Encrypt, cert-manager)
  • load-balancing-patterns - Advanced load balancing architecture and decision frameworks
  • deploying-applications - Application deployment strategies with nginx integration
  • security-hardening - Complete server security beyond nginx-specific configuration
  • configuring-firewalls - Firewall rules for HTTP/HTTPS access
  • dns-management - DNS configuration for nginx virtual hosts
  • kubernetes-operations - nginx Ingress Controller for Kubernetes
相关技能:
  • 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

Additional Resources

额外资源

Progressive Disclosure:
  • references/installation-guide.md
    - Detailed installation for all platforms
  • references/configuration-structure.md
    - Complete nginx.conf anatomy
  • references/static-sites.md
    - Static hosting patterns (basic, SPA, PHP)
  • references/reverse-proxy.md
    - Advanced proxy scenarios and API gateway patterns
  • references/load-balancing.md
    - All algorithms, health checks, sticky sessions
  • references/ssl-tls-config.md
    - Complete TLS configuration and certificate setup
  • references/performance-tuning.md
    - Workers, caching, compression, buffers
  • references/security-hardening.md
    - Rate limiting, headers, access control
  • references/troubleshooting.md
    - Common errors and debugging techniques
Working Examples:
  • examples/static-site/
    - Static website and SPA configurations
  • examples/reverse-proxy/
    - Node.js, WebSocket, API gateway examples
  • examples/load-balancing/
    - All load balancing algorithms
  • examples/ssl-tls/
    - Modern TLS and mTLS configurations
  • examples/performance/
    - High-traffic optimization and caching
  • examples/security/
    - Rate limiting and security hardening
Reusable Snippets:
  • snippets/ssl-modern.conf
    - Modern TLS configuration
  • snippets/proxy-params.conf
    - Standard proxy headers
  • snippets/security-headers.conf
    - OWASP security headers
  • snippets/cache-static.conf
    - Static asset caching
进阶参考文档:
  • references/installation-guide.md
    - 全平台详细安装指南
  • references/configuration-structure.md
    - Nginx.conf完整解析
  • references/static-sites.md
    - 静态站点托管方案(基础、单页应用、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/
    - 静态网站与单页应用配置
  • 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
    - 静态资源缓存配置