Nginx 配置完全指南
Nginx 是高性能的 HTTP 和反向代理服务器,以低内存消耗、高并发处理能力著称,是全球最流行的 Web 服务器之一。
📦 安装 Nginx
# Debian/Ubuntu
sudo apt update
sudo apt install nginx
# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx
# 启动服务
sudo systemctl start nginx
sudo systemctl enable nginx
# 验证安装
nginx -v
📁 配置文件结构
# 主配置文件
/etc/nginx/nginx.conf
# 虚拟主机配置
/etc/nginx/conf.d/*.conf
/etc/nginx/sites-enabled/*
# 配置语法检查
nginx -t
# 重新加载配置
nginx -s reload
基本结构
# 全局块
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# events 块
events {
worker_connections 1024;
}
# http 块
http {
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent"';
# 引入其他配置
include /etc/nginx/conf.d/*.conf;
}
🌐 虚拟主机
基本虚拟主机
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
多站点配置
# /etc/nginx/conf.d/site1.conf
server {
listen 80;
server_name site1.com;
root /var/www/site1;
}
# /etc/nginx/conf.d/site2.conf
server {
listen 80;
server_name site2.com;
root /var/www/site2;
}
默认服务器
server {
listen 80 default_server;
server_name _;
return 444; # 直接关闭连接
}
🔄 反向代理
基本反向代理
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;
}
}
带路径的反向代理
server {
listen 80;
server_name example.com;
# API 代理
location /api/ {
proxy_pass http://127.0.0.1:8080/;
}
# 静态文件
location / {
root /var/www/html;
}
}
WebSocket 代理
server {
listen 80;
server_name ws.example.com;
location /ws/ {
proxy_pass http://127.0.0.1:3000/ws/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
}
🔒 SSL/HTTPS 配置
Let's Encrypt 免费证书
# 安装 certbot
sudo apt install certbot python3-certbot-nginx
# 获取证书
sudo certbot --nginx -d example.com -d www.example.com
# 自动续期
certbot renew --dry-run
手动配置 SSL
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 优化
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
# HSTS
add_header Strict-Transport-Security "max-age=63072000" always;
root /var/www/example.com;
}
# HTTP 重定向到 HTTPS
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}
⚖️ 负载均衡
基本负载均衡
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 example.com;
location / {
proxy_pass http://backend;
}
}
负载均衡策略
# 轮询(默认)
upstream backend {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
# 加权轮询
upstream backend {
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=1;
}
# IP Hash(会话保持)
upstream backend {
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
# 最少连接
upstream backend {
least_conn;
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;
}
📂 Location 匹配规则
匹配优先级
# 1. 精确匹配 (=)
location = /api {
# 只匹配 /api
}
# 2. 前缀匹配 (^~)
location ^~ /static/ {
# 匹配以 /static/ 开头的请求
}
# 3. 正则匹配 (~)
location ~ \.php$ {
# 匹配 .php 结尾的请求
}
# 4. 普通前缀匹配
location /api/ {
# 匹配以 /api/ 开头的请求
}
# 5. 默认匹配
location / {
# 匹配所有请求
}
常用示例
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
# 禁止访问特定目录
location ~ ^/(wp-admin|wp-includes) {
deny all;
}
🚀 性能优化
基本优化
# 工作进程数(通常等于 CPU 核心数)
worker_processes auto;
# 每个进程的最大连接数
events {
worker_connections 1024;
multi_accept on;
use epoll;
}
http {
# 开启高效文件传输
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 连接超时
keepalive_timeout 65;
# 缓冲区大小
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 4k;
}
Gzip 压缩
http {
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_min_length 256;
}
缓存配置
# 代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_pass http://backend;
}
}
🔐 安全配置
安全 Headers
server {
# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN" always;
# 防止 MIME 类型嗅探
add_header X-Content-Type-Options "nosniff" always;
# XSS 保护
add_header X-XSS-Protection "1; mode=block" always;
# CSP
add_header Content-Security-Policy "default-src 'self' https: data: 'unsafe-inline'" always;
# 隐藏 Nginx 版本
server_tokens off;
}
限流配置
http {
# 定义限流区域
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
}
server {
location /api/ {
# 限制请求速率
limit_req zone=api burst=20 nodelay;
# 限制连接数
limit_conn addr 10;
proxy_pass http://backend;
}
}
IP 白名单/黑名单
# 允许特定 IP
location /admin/ {
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
}
# 拒绝特定 IP
deny 192.168.1.100;
deny 192.168.1.0/24;
📝 日志配置
自定义日志格式
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
log_format json escape=json '{'
'"time":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}';
}
server {
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
}
日志切割
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 nginx adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
🛠️ 实用配置片段
PHP-FPM 配置
server {
listen 80;
server_name php.example.com;
root /var/www/php;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
SPA 应用配置
server {
listen 80;
server_name spa.example.com;
root /var/www/spa;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
# API 代理
location /api/ {
proxy_pass http://127.0.0.1:3000/;
}
}
文件服务器
server {
listen 80;
server_name files.example.com;
location / {
root /var/www/files;
autoindex on; # 开启目录浏览
autoindex_exact_size off;
autoindex_localtime on;
}
}
跨域配置 (CORS)
server {
location /api/ {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
if ($request_method = 'OPTIONS') {
return 204;
}
proxy_pass http://backend;
}
}
📚 常用命令速查
# 检查配置语法
nginx -t
# 重新加载配置(不中断服务)
nginx -s reload
# 停止 Nginx
nginx -s stop
# 优雅停止(处理完当前请求)
nginx -s quit
# 查看 Nginx 版本和编译参数
nginx -V
# 测试配置并退出
nginx -T
# 发送信号重启
kill -HUP $(cat /var/run/nginx.pid)
💡 最佳实践
- 配置分离:每个站点一个配置文件,放在
conf.d/或sites-enabled/ - 总是先测试:修改后先
nginx -t检查语法 - 备份配置:修改前备份原配置
- 使用变量:避免硬编码,使用
$server_name等变量 - 限制访问:敏感目录设置 IP 白名单
- 开启日志:便于排查问题
- 定期更新:保持 Nginx 版本最新
Nginx 的配置灵活强大,掌握这些基础配置,你就能应对 90% 的 Web 服务器和反向代理需求。 🚀