Nginx配置详解
约 1416 字大约 5 分钟
nginxconfiguration
2025-07-11
概述
Nginx是高性能的HTTP服务器和反向代理,以事件驱动的异步架构著称,能以极低的资源消耗处理大量并发连接。本文系统讲解Nginx的配置结构、核心指令和常见应用场景。
配置文件结构
基本配置框架:
# main 全局块
user nginx;
worker_processes auto; # 通常设为CPU核心数
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
# events 块
events {
worker_connections 4096; # 每个worker的最大连接数
use epoll; # Linux推荐
multi_accept on; # 一次accept多个连接
}
# http 块
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
access_log /var/log/nginx/access.log main;
# 性能优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 1000;
# Gzip压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 4;
gzip_min_length 256;
gzip_types text/plain text/css application/json application/javascript
text/xml application/xml application/xml+rss text/javascript
image/svg+xml;
# 包含其他配置
include /etc/nginx/conf.d/*.conf;
}Location匹配规则
Location匹配是Nginx配置的核心,按优先级从高到低排列:
# 1. 精确匹配(最高优先级)
location = /api/health {
return 200 "OK";
}
# 2. 前缀匹配(^~ 修饰符,不再检查正则)
location ^~ /static/ {
root /var/www;
}
# 3. 正则匹配(~ 区分大小写,~* 不区分)
location ~ \.(jpg|jpeg|png|gif)$ {
expires 30d;
}
location ~* \.css$ {
expires 7d;
}
# 4. 普通前缀匹配(最长前缀优先)
location /api/ {
proxy_pass http://backend;
}
# 5. 默认匹配
location / {
root /var/www/html;
try_files $uri $uri/ /index.html;
}反向代理
upstream backend {
server 10.0.0.1:8080 weight=3;
server 10.0.0.2:8080 weight=2;
server 10.0.0.3:8080 backup; # 备份服务器
# 负载均衡算法
# 默认轮询 (round-robin)
# least_conn; # 最少连接
# ip_hash; # IP哈希(会话保持)
# hash $request_uri consistent; # 一致性哈希
# 健康检查(被动)
# max_fails=3 fail_timeout=30s 为默认值
# 连接池
keepalive 32; # 保持的上游空闲连接数
keepalive_timeout 60s;
keepalive_requests 1000;
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection ""; # 启用keepalive
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_connect_timeout 5s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 缓冲设置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
# 错误处理
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 3;
proxy_next_upstream_timeout 10s;
}
}负载均衡策略
# 加权轮询
upstream app {
server 10.0.0.1:8080 weight=5;
server 10.0.0.2:8080 weight=3;
server 10.0.0.3:8080 weight=2;
}
# 最少连接
upstream app {
least_conn;
server 10.0.0.1:8080;
server 10.0.0.2:8080;
}
# 一致性哈希(基于URI)
upstream app {
hash $request_uri consistent;
server 10.0.0.1:8080;
server 10.0.0.2:8080;
}SSL终止
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/ssl/certs/fullchain.pem;
ssl_certificate_key /etc/ssl/private/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 valid=300s;
add_header Strict-Transport-Security "max-age=63072000" always;
location / {
proxy_pass http://backend;
}
}缓存配置
# http块中定义缓存区
http {
proxy_cache_path /var/cache/nginx
levels=1:2
keys_zone=my_cache:10m # 10MB内存存储key
max_size=10g # 最大磁盘空间
inactive=60m # 60分钟未访问则删除
use_temp_path=off;
server {
location /api/ {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m; # 200/302缓存10分钟
proxy_cache_valid 404 1m; # 404缓存1分钟
proxy_cache_key "$scheme$host$request_uri";
proxy_cache_use_stale error timeout updating
http_500 http_502 http_503;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://backend;
}
}
}限流(Rate Limiting)
http {
# 定义限流区域
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login_limit:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
# API限流:10 req/s,允许突发20
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
limit_req_status 429;
proxy_pass http://backend;
}
# 登录限流:1 req/s
location /login {
limit_req zone=login_limit burst=5;
limit_req_status 429;
proxy_pass http://backend;
}
# 并发连接限制
location /download/ {
limit_conn conn_limit 5; # 每IP最多5个并发
limit_rate 500k; # 每连接限速500KB/s
limit_rate_after 10m; # 前10MB不限速
}
}
}访问控制
# IP黑白名单
location /admin/ {
allow 10.0.0.0/8;
allow 172.16.0.0/12;
deny all;
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
# 基于geo模块的访问控制
geo $blocked {
default 0;
1.2.3.0/24 1;
5.6.7.0/24 1;
}
server {
if ($blocked) {
return 403;
}
}
# 防盗链
location ~* \.(jpg|jpeg|png|gif|webp)$ {
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
}
}常用配置片段
# WebSocket代理
location /ws/ {
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400s;
}
# 静态文件服务
location /static/ {
alias /var/www/static/;
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
# SPA单页应用
location / {
root /var/www/app;
try_files $uri $uri/ /index.html;
}
# 自定义错误页
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
internal;
}调试与监控
# 测试配置语法
nginx -t
# 重载配置(不中断服务)
nginx -s reload
# 查看编译模块
nginx -V
# 启用stub_status监控
location /nginx_status {
stub_status;
allow 10.0.0.0/8;
deny all;
}
# 输出示例:
# Active connections: 291
# server accepts handled requests
# 16630948 16630948 31070465
# Reading: 6 Writing: 179 Waiting: 106
# 日志分析
# 统计状态码分布
awk '{print $9}' access.log | sort | uniq -c | sort -rn
# 统计最慢请求
awk '{print $NF, $7}' access.log | sort -rn | head -20总结
Nginx的配置灵活且强大,从静态文件服务到反向代理、负载均衡、缓存、限流和SSL终止,覆盖了Web架构的方方面面。掌握location匹配规则、upstream配置和常用指令,是高效运维的基础。在生产环境中,建议使用include模块化管理配置,并通过nginx -t在应用前验证配置正确性。
贡献者
更新日志
2026/3/14 13:09
查看所有更新日志
9f6c2-feat: organize wiki content and refresh site setup于