2026年3月14日
Nginx 配置指南 - 从入门到精通
Nginx 是一款高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 服务器。以其高并发、低内存占用而闻名。
Nginx 简介
核心特点
- 高并发:支持数万并发连接
- 低内存:万级连接仅占用几 MB 内存
- 模块化:丰富的模块生态系统
- 热部署:支持配置热更新
- 反向代理:强大的代理功能
应用场景
| 场景 | 说明 |
|---|---|
| Web 服务器 | 静态资源服务 |
| 反向代理 | 代理后端应用 |
| 负载均衡 | 分发请求到多台服务器 |
| 缓存服务器 | 缓存后端响应 |
| API 网关 | 统一入口管理 |
安装 Nginx
Ubuntu/Debian
sudo apt update
sudo apt install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
CentOS/RHEL
sudo yum install epel-release -y
sudo yum install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
源码编译安装
# 安装依赖
sudo apt install -y build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev
# 下载源码
wget http://nginx.org/download/nginx-1.24.0.tar.gz
tar -xzf nginx-1.24.0.tar.gz
cd nginx-1.24.0
# 配置
./configure --prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-http_stub_status_module
# 编译安装
make && sudo make install
验证安装
nginx -v
curl http://localhost
配置文件结构
主配置文件
# /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
配置结构
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 额外配置
├── sites-available/ # 可用站点
├── sites-enabled/ # 启用站点
└── snippets/ # 配置片段
基础配置
静态网站
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
目录浏览
server {
listen 80;
server_name files.example.com;
location / {
root /var/www/files;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}
}
禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
反向代理
基础反向代理
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
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;
}
}
WebSocket 代理
location /ws/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
代理缓冲配置
location / {
proxy_pass http://backend;
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
}
负载均衡
基础配置
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}
server {
listen 80;
server_name lb.example.com;
location / {
proxy_pass http://backend;
}
}
负载均衡策略
| 策略 | 说明 |
|---|---|
| 轮询 | 默认,按顺序分配 |
| weight | 加权轮询 |
| ip_hash | 按 IP 分配 |
| least_conn | 最少连接 |
| hash | 按 key 哈希 |
加权轮询
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 哈希
upstream backend {
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
健康检查
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;
}
HTTPS 配置
基础 HTTPS
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
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_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
location / {
root /var/www/html;
}
}
# HTTP 重定向 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
Let’s Encrypt 免费证书
# 安装 Certbot
sudo apt install certbot python3-certbot-nginx
# 获取证书
sudo certbot --nginx -d example.com -d www.example.com
# 自动续期
sudo certbot renew --dry-run
SSL 优化配置
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Frame-Options DENY always;
add_header X-Content-Type-Options nosniff always;
缓存配置
静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
代理缓存
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 {
location / {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500;
add_header X-Cache-Status $upstream_cache_status;
}
}
}
FastCGI 缓存
http {
fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2
keys_zone=fastcgi_cache:10m max_size=1g inactive=60m;
server {
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_cache fastcgi_cache;
fastcgi_cache_valid 200 10m;
}
}
}
Gzip 压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml
application/xml+rss
application/x-javascript;
gzip_disable "msie6";
访问控制
IP 白名单
location /admin {
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
}
基础认证
# 创建密码文件
sudo apt install apache2-utils
htpasswd -c /etc/nginx/.htpasswd admin
location /admin {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
限流配置
http {
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
limit_conn conn_limit 10;
}
}
}
日志配置
自定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'rt=$request_time uct="$upstream_connect_time" '
'uht="$upstream_header_time" urt="$upstream_response_time"';
access_log /var/log/nginx/access.log main;
按域名分离日志
server {
server_name example.com;
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
}
日志轮转
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ -f /run/nginx.pid ] && kill -USR1 `cat /run/nginx.pid`
endscript
}
性能优化
基础优化
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 65535;
use epoll;
multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 10000;
reset_timedout_connection on;
client_body_timeout 10;
send_timeout 2;
}
文件描述符优化
# /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
内核参数优化
# /etc/sysctl.conf
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_tw_reuse = 1
常用命令
# 测试配置
nginx -t
# 重载配置
nginx -s reload
# 停止服务
nginx -s stop
# 平滑停止
nginx -s quit
# 重新打开日志
nginx -s reopen
# 查看版本和编译参数
nginx -V
# 查看 Nginx 进程
ps aux | grep nginx
常见问题
Q: 502 Bad Gateway?
检查后端服务是否运行,端口是否正确。
Q: 504 Gateway Timeout?
增加超时时间:
proxy_read_timeout 300;
proxy_connect_timeout 300;
proxy_send_timeout 300;
Q: 上传文件大小限制?
client_max_body_size 100M;
Q: 如何查看当前连接数?
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
总结
Nginx 是 Web 服务器和反向代理的首选方案。掌握 Nginx 配置对于运维和开发人员都非常重要。本文涵盖了:
- 安装和基础配置
- 反向代理和负载均衡
- HTTPS 和缓存配置
- 访问控制和性能优化
建议在实际项目中逐步实践,深入理解每个配置项的作用。