configuring-nginx
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseConfiguring 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 nginxRHEL/CentOS/Rocky:
bash
sudo dnf install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginxDocker:
bash
docker run -d -p 80:80 -v /path/to/config:/etc/nginx/conf.d nginx:alpineUbuntu/Debian系统:
bash
sudo apt update && sudo apt install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginxRHEL/CentOS/Rocky系统:
bash
sudo dnf install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginxDocker部署:
bash
docker run -d -p 80:80 -v /path/to/config:/etc/nginx/conf.d nginx:alpineQuick 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 nginxSee for SPA configurations and advanced patterns.
references/static-sites.md从指定目录托管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.mdReverse 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 for WebSocket proxying and API gateway patterns.
references/reverse-proxy.md将请求代理至后端应用服务器:
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.mdSSL/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 for complete TLS configuration and certificate setup.
references/ssl-tls-config.md通过现代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.mdCore 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:
- - Main configuration
/etc/nginx/nginx.conf - - Available site configs
/etc/nginx/sites-available/ - - Enabled sites (symlinks)
/etc/nginx/sites-enabled/ - - Additional configs
/etc/nginx/conf.d/*.conf - - Reusable config snippets
/etc/nginx/snippets/
See for detailed anatomy.
references/configuration-structure.mdNginx采用分层配置上下文:
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.mdLocation Matching Priority
位置匹配优先级
nginx evaluates location blocks in this order:
- - Exact match (highest priority)
location = /exact - - Prefix match, stop searching
location ^~ /prefix - - Regex, case-sensitive
location ~ \.php$ - - Regex, case-insensitive
location ~* \.(jpg|png)$ - - Prefix match (lowest priority)
location /
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块:
- - 精确匹配(优先级最高)
location = /exact - - 前缀匹配,匹配后停止搜索
location ^~ /prefix - - 正则匹配,区分大小写
location ~ \.php$ - - 正则匹配,不区分大小写
location ~* \.(jpg|png)$ - - 前缀匹配(优先级最低)
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 and include with:
/etc/nginx/snippets/proxy-params.confnginx
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.confnginx
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 for weighted load balancing and advanced patterns.
references/load-balancing.md在多台后端服务器间分发流量:
轮询(默认):
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.mdWebSocket 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
undefinedIn 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
undefinedIn 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:**
```nginxuser www-data;
worker_processes auto; # 每个CPU核心对应一个进程
worker_rlimit_nofile 65535;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
**Gzip压缩:**
```nginxIn 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:**
```nginxgzip 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;
**代理缓存:**
```nginxDefine 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
undefinedCreate /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 (, mod_php, legacy apps), Caddy (auto-HTTPS, simpler config), Traefik (dynamic containers), Envoy (service mesh).
.htaccess选择Nginx的场景: 对性能要求严苛的工作负载(支持10000+并发连接)、反向代理、负载均衡、静态文件托管、现代应用栈。
选择替代方案的场景: Apache(需要、mod_php或遗留应用)、Caddy(自动HTTPS、配置更简洁)、Traefik(动态容器场景)、Envoy(服务网格)。
.htaccessSafety Checklist
安全检查清单
Before deploying nginx configurations:
- Test configuration syntax:
sudo nginx -t - Use reload, not restart: (zero downtime)
sudo systemctl reload nginx - 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 (), check logs (), verify backend ().
sudo nginx -t/var/log/nginx/error.logcurl http://127.0.0.1:3000Common errors: 502 (backend down), 504 (timeout - increase ), 413 (upload size - set ).
proxy_read_timeoutclient_max_body_sizeSee for complete debugging guide.
references/troubleshooting.md快速修复步骤: 测试配置()、检查日志()、验证后端服务()。
sudo nginx -t/var/log/nginx/error.logcurl http://127.0.0.1:3000常见错误: 502(后端服务下线)、504(超时 - 增大值)、413(上传文件过大 - 设置)。
proxy_read_timeoutclient_max_body_size如需完整调试指南,请参考。
references/troubleshooting.mdIntegration 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:
- - Detailed installation for all platforms
references/installation-guide.md - - Complete nginx.conf anatomy
references/configuration-structure.md - - Static hosting patterns (basic, SPA, PHP)
references/static-sites.md - - Advanced proxy scenarios and API gateway patterns
references/reverse-proxy.md - - All algorithms, health checks, sticky sessions
references/load-balancing.md - - Complete TLS configuration and certificate setup
references/ssl-tls-config.md - - Workers, caching, compression, buffers
references/performance-tuning.md - - Rate limiting, headers, access control
references/security-hardening.md - - Common errors and debugging techniques
references/troubleshooting.md
Working Examples:
- - Static website and SPA configurations
examples/static-site/ - - Node.js, WebSocket, API gateway examples
examples/reverse-proxy/ - - All load balancing algorithms
examples/load-balancing/ - - Modern TLS and mTLS configurations
examples/ssl-tls/ - - High-traffic optimization and caching
examples/performance/ - - Rate limiting and security hardening
examples/security/
Reusable Snippets:
- - Modern TLS configuration
snippets/ssl-modern.conf - - Standard proxy headers
snippets/proxy-params.conf - - OWASP security headers
snippets/security-headers.conf - - Static asset caching
snippets/cache-static.conf
进阶参考文档:
- - 全平台详细安装指南
references/installation-guide.md - - Nginx.conf完整解析
references/configuration-structure.md - - 静态站点托管方案(基础、单页应用、PHP)
references/static-sites.md - - 进阶代理场景与API网关方案
references/reverse-proxy.md - - 所有负载均衡算法详解
references/load-balancing.md - - 完整TLS配置与证书设置
references/ssl-tls-config.md - - 工作进程、缓存、压缩、缓冲区优化
references/performance-tuning.md - - 速率限制与安全加固
references/security-hardening.md - - 常见错误与调试技巧
references/troubleshooting.md
实战示例:
- - 静态网站与单页应用配置
examples/static-site/ - - Node.js、WebSocket、API网关示例
examples/reverse-proxy/ - - 所有负载均衡算法示例
examples/load-balancing/ - - 现代TLS与mTLS配置
examples/ssl-tls/ - - 高流量场景优化与缓存配置
examples/performance/ - - 速率限制与安全加固示例
examples/security/
可复用配置片段:
- - 现代TLS配置
snippets/ssl-modern.conf - - 标准代理标头
snippets/proxy-params.conf - - OWASP安全标头
snippets/security-headers.conf - - 静态资源缓存配置
snippets/cache-static.conf