Nginx 配置完整指南
目录
1. 反向代理
1.1 基础反向代理
nginx
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:8080;
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;
}
}
1.2 多服务路由
nginx
server {
listen 80;
server_name api.example.com;
# 用户服务
location /user/ {
proxy_pass http://127.0.0.1:8081;
proxy_set_header Host $host;
}
# 订单服务
location /order/ {
proxy_pass http://127.0.0.1:8082;
proxy_set_header Host $host;
}
# 商品服务
location /product/ {
proxy_pass http://127.0.0.1:8083;
proxy_set_header Host $host;
}
}
1.3 路径重写
nginx
# 移除前缀
location /api/ {
proxy_pass http://backend/; # 注意结尾的 / 会去掉 /api/
}
# 保留前缀
location /api/ {
proxy_pass http://backend; # 保留 /api/
}
# 完全重写路径
location /old-path/ {
rewrite ^/old-path/(.*)$ /new-path/$1 break;
proxy_pass http://backend;
}
2. 负载均衡
2.1 定义上游服务器组
nginx
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}
2.2 负载均衡策略
轮询(默认)
nginx
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}
加权轮询
nginx
upstream backend {
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=2;
server 192.168.1.12:8080 weight=1;
}
IP 哈希(会话保持)
nginx
upstream backend {
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}
最少连接
nginx
upstream backend {
least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}
2.3 健康检查
nginx
upstream backend {
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 backup; # 备用服务器
}
参数说明:
max_fails: 最大失败次数fail_timeout: 失败后暂停时间backup: 备用服务器down: 手动标记为不可用
2.4 长连接
nginx
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
keepalive 32; # 最多保持32个空闲长连接
}
server {
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
2.5 故障转移配置
nginx
upstream backend {
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 backup;
}
server {
location / {
proxy_pass http://backend;
# 定义何时切换到下一台服务器
proxy_next_upstream error timeout http_500 http_502 http_503;
proxy_next_upstream_tries 2; # 最多尝试2台服务器
# 超时配置
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
3. 静态资源服务
3.1 基础配置
nginx
server {
listen 80;
server_name static.example.com;
location / {
root /var/www/html;
index index.html;
}
}
3.2 别名配置
nginx
server {
location /images/ {
alias /data/images/;
}
location /files/ {
alias /data/files/;
}
}
root vs alias:
root /var/www+/static/file.txt→/var/www/static/file.txtalias /var/www+/static/file.txt→/var/www/file.txt
3.3 浏览器缓存
nginx
server {
listen 80;
# 静态文件缓存30天
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
root /var/www;
expires 30d;
add_header Cache-Control "public, immutable";
}
# HTML文件不缓存
location ~* \.html$ {
root /var/www;
add_header Cache-Control "no-cache, no-store, must-revalidate";
}
}
3.4 开启目录浏览
nginx
server {
listen 80;
location /downloads/ {
root /var/www;
autoindex on; # 开启目录浏览
autoindex_exact_size off; # 文件大小以KB/MB显示
autoindex_localtime on; # 显示本地时间
charset utf-8; # 支持中文文件名
}
}
3.5 Gzip 压缩
nginx
http {
gzip on;
gzip_vary on;
gzip_min_length 1k;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss
application/rss+xml font/truetype font/opentype
application/vnd.ms-fontobject image/svg+xml;
server {
location / {
root /var/www;
}
}
}
4. HTTPS/SSL配置
4.1 基础HTTPS
nginx
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
location / {
proxy_pass http://backend;
}
}
4.2 HTTP自动跳转HTTPS
nginx
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
location / {
proxy_pass http://backend;
}
}
4.3 SSL优化配置
nginx
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
# SSL协议
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
# 加密套件
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
# SSL会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
location / {
proxy_pass http://backend;
}
}
4.4 Let's Encrypt证书
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_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
location / {
proxy_pass http://backend;
}
}
5. 限流配置
5.1 基于IP限流
nginx
http {
# 定义限流区域:每秒10个请求,缓冲区10MB
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
server {
listen 80;
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
proxy_pass http://backend;
}
}
}
参数说明:
rate: 限流速率(10r/s = 每秒10个请求)burst: 允许的突发请求数nodelay: 不延迟处理,超过立即拒绝
5.2 基于连接数限流
nginx
http {
# 每个IP最多10个连接
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
listen 80;
location / {
limit_conn conn_limit 10;
proxy_pass http://backend;
}
}
}
5.3 限流响应
nginx
http {
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
server {
listen 80;
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
limit_req_status 429; # 返回429状态码
# 自定义错误页面
error_page 429 =200 /ratelimit.json;
}
location = /ratelimit.json {
default_type application/json;
return 200 '{"code":429,"message":"请求过于频繁,请稍后重试"}';
}
}
}
5.4 不同路径不同限流
nginx
http {
# API限流:每秒100个请求
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s;
# 登录接口限流:每分钟5个请求
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=5r/m;
server {
listen 80;
location /api/ {
limit_req zone=api_limit burst=50 nodelay;
proxy_pass http://backend;
}
location /api/login {
limit_req zone=login_limit burst=2 nodelay;
proxy_pass http://backend;
}
}
}
6. 缓存配置
6.1 代理缓存
nginx
http {
# 定义缓存路径
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m
max_size=1g inactive=60m use_temp_path=off;
server {
listen 80;
location / {
proxy_cache my_cache;
proxy_cache_valid 200 60m; # 200响应缓存60分钟
proxy_cache_valid 404 1m; # 404响应缓存1分钟
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_pass http://backend;
}
}
}
参数说明:
levels: 缓存目录层级keys_zone: 共享内存区域,名称:大小max_size: 最大缓存大小inactive: 缓存多久未被访问后删除
6.2 忽略指定请求头
nginx
proxy_cache my_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
# 忽略特定请求头的缓存
proxy_no_cache $cookie_user_login;
proxy_cache_bypass $cookie_user_login;
6.3 缓存控制
nginx
location /api/ {
proxy_cache my_cache;
proxy_cache_valid 200 60m;
# GET请求缓存,POST不缓存
proxy_cache_methods GET HEAD;
# 忽略Set-Cookie头
proxy_ignore_headers Set-Cookie;
# 不缓存特定条件
proxy_cache_bypass $http_pragma $http_authorization;
proxy_pass http://backend;
}
6.4 FastCGI缓存
nginx
http {
fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2
keys_zone=fastcgi_cache:10m max_size=1g inactive=60m;
server {
listen 80;
location ~ \.php$ {
fastcgi_cache fastcgi_cache;
fastcgi_cache_valid 200 60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
}
}
}
7. 安全配置
7.1 隐藏Nginx版本号
nginx
http {
server_tokens off;
}
7.2 防止点击劫持
nginx
server {
listen 80;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
location / {
proxy_pass http://backend;
}
}
7.3 限制请求方法
nginx
server {
listen 80;
# 只允许GET、POST、HEAD
if ($request_method !~ ^(GET|POST|HEAD)$ ) {
return 405;
}
location / {
proxy_pass http://backend;
}
}
7.4 限制上传文件大小
nginx
server {
listen 80;
# 全局限制10MB
client_max_body_size 10m;
location /upload/ {
# 上传接口限制100MB
client_max_body_size 100m;
proxy_pass http://backend;
}
}
7.5 IP白名单/黑名单
nginx
server {
listen 80;
# IP白名单
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
# 或 IP黑名单
# deny 192.168.1.100;
# deny 192.168.1.200;
# allow all;
location / {
proxy_pass http://backend;
}
}
7.6 防止敏感文件泄露
nginx
server {
listen 80;
# 拒绝访问隐藏文件
location ~ /\. {
deny all;
}
# 拒绝访问备份文件
location ~ \.(bak|old|tmp|log|sql|env)$ {
deny all;
}
# 拒绝访问特定目录
location ~ ^/(\.git|\.svn|\.hg)/ {
deny all;
}
location / {
proxy_pass http://backend;
}
}
7.7 防止SQL注入和XSS攻击
nginx
server {
listen 80;
# 拦截常见攻击
if ($args ~* "union.*select.*\(") {
return 403;
}
if ($args ~* "concat.*\(") {
return 403;
}
if ($args ~* "<script>") {
return 403;
}
location / {
proxy_pass http://backend;
}
}
8. 日志配置
8.1 访问日志
nginx
http {
# 定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'$request_time $upstream_response_time';
log_format json escape=json '{'
'"time_local":"$time_local",'
'"remote_addr":"$remote_addr",'
'"remote_user":"$remote_user",'
'"request":"$request",'
'"status":"$status",'
'"body_bytes_sent":"$body_bytes_sent",'
'"request_time":"$request_time",'
'"http_referrer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}';
access_log /var/log/nginx/access.log main;
}
8.2 错误日志
nginx
http {
# 错误日志级别:debug|info|notice|warn|error|crit
error_log /var/log/nginx/error.log warn;
}
server {
# 单个server的错误日志
error_log /var/log/nginx/example_error.log error;
}
8.3 关闭特定日志
nginx
server {
listen 80;
# 健康检查不记录日志
location /health {
access_log off;
return 200 "OK";
}
# 静态资源不记录日志
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
access_log off;
root /var/www;
}
location / {
proxy_pass http://backend;
}
}
8.4 日志切割
bash
#!/bin/bash
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
9. WebSocket支持
9.1 WebSocket代理
nginx
http {
upstream websocket {
server 192.168.1.10:8080;
}
server {
listen 80;
server_name ws.example.com;
location / {
proxy_pass http://websocket;
# WebSocket配置
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# 超时配置
proxy_connect_timeout 7d;
proxy_send_timeout 7d;
proxy_read_timeout 7d;
}
}
}
9.2 Socket.IO支持
nginx
server {
listen 80;
location /socket.io/ {
proxy_pass http://socket_io_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
9.3 多WebSocket服务
nginx
http {
upstream chat_ws {
server 192.168.1.10:8080;
}
upstream notification_ws {
server 192.168.1.20:8081;
}
server {
listen 80;
location /chat/ {
proxy_pass http://chat_ws;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location /notification/ {
proxy_pass http://notification_ws;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
}
10. 模块化配置
10.1 目录结构
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/
│ ├── upstream.conf # 负载均衡配置
│ ├── proxy.conf # 代理通用配置
│ ├── ssl.conf # SSL配置
│ ├── cache.conf # 缓存配置
│ ├── limit.conf # 限流配置
│ ├── security.conf # 安全配置
│ └── logging.conf # 日志配置
├── sites-available/ # 可用站点配置
│ ├── default.conf
│ ├── api.example.com.conf
│ ├── web.example.com.conf
│ └── static.example.com.conf
└── sites-enabled/ # 已启用站点(软链接)
├── api.example.com.conf -> ../sites-available/api.example.com.conf
└── web.example.com.conf -> ../sites-available/web.example.com.conf
10.2 主配置文件 nginx.conf
nginx
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
worker_connections 1024;
use epoll;
}
http {
# 基础配置
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志配置
include /etc/nginx/conf.d/logging.conf;
# 性能优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip压缩
include /etc/nginx/conf.d/gzip.conf;
# 包含通用配置
include /etc/nginx/conf.d/*.conf;
# 包含站点配置
include /etc/nginx/sites-enabled/*.conf;
}
10.3 upstream.conf - 负载均衡
nginx
# 用户服务
upstream user-service {
server 192.168.1.10:8081 weight=3;
server 192.168.1.11:8081 weight=2;
server 192.168.1.12:8081 backup;
keepalive 32;
}
# 订单服务
upstream order-service {
server 192.168.1.20:8082;
server 192.168.1.21:8082;
server 192.168.1.22:8082;
keepalive 32;
}
# 商品服务
upstream product-service {
least_conn;
server 192.168.1.30:8083;
server 192.168.1.31:8083;
server 192.168.1.32:8083;
keepalive 32;
}
10.4 proxy.conf - 代理通用配置
nginx
# HTTP版本和连接
proxy_http_version 1.1;
proxy_set_header Connection "";
# 请求头设置
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_set_header X-Forwarded-Host $server_name;
# 超时配置
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 重试配置
proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
proxy_next_upstream_tries 2;
# 缓冲配置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
# WebSocket支持
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
10.5 ssl.conf - SSL配置
nginx
# SSL协议
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
# 加密套件
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
# SSL会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
10.6 limit.conf - 限流配置
nginx
# API限流
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s;
# 登录接口限流
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=5r/m;
# 连接数限制
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
10.7 security.conf - 安全配置
nginx
# 隐藏版本号
server_tokens 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;
# 限制请求大小
client_max_body_size 10m;
client_body_buffer_size 128k;
10.8 cache.conf - 缓存配置
nginx
# 代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=proxy_cache:10m
max_size=1g inactive=60m use_temp_path=off;
# FastCGI缓存
fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2
keys_zone=fastcgi_cache:10m max_size=1g inactive=60m;
10.9 logging.conf - 日志配置
nginx
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'$request_time $upstream_response_time';
log_format json escape=json '{'
'"time_local":"$time_local",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":"$status",'
'"request_time":"$request_time",'
'"upstream_response_time":"$upstream_response_time"'
'}';
# 访问日志
access_log /var/log/nginx/access.log main;
# 错误日志
error_log /var/log/nginx/error.log warn;
10.10 gzip.conf - Gzip配置
nginx
gzip on;
gzip_vary on;
gzip_min_length 1k;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss
application/rss+xml font/truetype font/opentype
application/vnd.ms-fontobject image/svg+xml;
gzip_disable "msie6";
10.11 站点配置示例
nginx
# sites-available/api.example.com.conf
server {
listen 80;
server_name api.example.com;
# 引入限流配置
location /api/ {
limit_req zone=api_limit burst=50 nodelay;
limit_conn conn_limit 10;
proxy_pass http://user-service;
include /etc/nginx/conf.d/proxy.conf;
}
location /order/ {
proxy_pass http://order-service;
include /etc/nginx/conf.d/proxy.conf;
}
location /product/ {
proxy_pass http://product-service;
include /etc/nginx/conf.d/proxy.conf;
}
}
nginx
# sites-available/web.example.com.conf
server {
listen 80;
server_name web.example.com;
# 静态资源
location /static/ {
root /var/www;
expires 30d;
}
# API代理
location /api/ {
proxy_pass http://user-service;
include /etc/nginx/conf.d/proxy.conf;
}
# 前端应用
location / {
root /var/www/web;
index index.html;
try_files $uri $uri/ /index.html;
}
}
常用命令
bash
# 测试配置
nginx -t
# 重新加载配置
nginx -s reload
# 停止服务
nginx -s stop
# 优雅停止
nginx -s quit
# 查看版本
nginx -v
# 查看编译参数
nginx -V
# 查看进程
ps aux | grep nginx
# 查看监听端口
netstat -tlnp | grep nginx
性能优化建议
- worker_processes: 设置为CPU核心数
- worker_connections: 根据并发量调整(默认1024)
- keepalive_timeout: 根据业务调整(默认65s)
- 启用sendfile: 高效文件传输
- 启用gzip: 减少传输数据量
- 启用缓存: 减少后端压力
- 调整buffer大小: 根据实际需求
- 使用长连接: 减少连接建立开销