基础配置
worker_processes 核心
设置工作进程数,通常设置为CPU核心数或auto自动检测
# 设置为auto自动检测CPU核心数
worker_processes auto;

# 或指定具体数值
worker_processes 4;
worker_connections 核心
每个工作进程的最大连接数,影响并发处理能力
events {
    worker_connections 1024;
    use epoll;  # Linux高性能网络IO模型
    multi_accept on;  # 一次接受所有新连接
}
include 常用
引入其他配置文件,便于模块化配置管理
# 引入mime.types文件类型映射
include /etc/nginx/mime.types;

# 引入conf.d目录下所有配置文件
include /etc/nginx/conf.d/*.conf;

# 引入sites-enabled目录下所有站点配置
include /etc/nginx/sites-enabled/*;
Server 配置
listen 必需
监听端口,可以指定IP地址和端口
server {
    # 监听80端口
    listen 80;
    
    # 监听指定IP的80端口
    listen 192.168.1.100:80;
    
    # 监听443端口并启用SSL
    listen 443 ssl http2;
    
    # IPv6监听
    listen [::]:80;
}
server_name 必需
服务器名称,可以是域名、IP或通配符
server {
    # 单个域名
    server_name example.com;
    
    # 多个域名
    server_name example.com www.example.com;
    
    # 通配符子域名
    server_name *.example.com;
    
    # 正则匹配
    server_name ~^(www\.)?(.+)$;
}
root & index 常用
设置网站根目录和默认首页文件
server {
    # 网站根目录
    root /var/www/html;
    
    # 默认首页文件
    index index.html index.htm index.php;
    
    # 字符编码
    charset utf-8;
}
Location 配置
匹配规则说明
Location用于匹配请求的URI,支持多种匹配方式
修饰符 说明 优先级
= 精确匹配 1(最高)
^~ 前缀匹配,匹配后停止搜索 2
~ 正则匹配(区分大小写) 3
~* 正则匹配(不区分大小写) 3
普通前缀匹配 4(最低)
常用Location示例
server {
    # 精确匹配
    location = / {
        root /var/www/html;
        index index.html;
    }
    
    # 静态文件匹配
    location ^~ /static/ {
        root /var/www/static;
        expires 30d;  # 缓存30天
    }
    
    # 正则匹配PHP文件
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
    }
    
    # 正则匹配图片文件(不区分大小写)
    location ~* \.(gif|jpg|jpeg|png|css|js)$ {
        root /var/www/images;
        expires 1d;
    }
    
    # 通用匹配(最低优先级)
    location / {
        try_files $uri $uri/ /index.html;
    }
}
反向代理配置
基础反向代理
将请求转发到后端服务器
location /api/ {
    # 后端服务器地址
    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;
    
    # 超时设置
    proxy_connect_timeout 60s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;
}
负载均衡配置
配置多个后端服务器实现负载均衡
# 定义上游服务器组
upstream backend_servers {
    # 轮询(默认)
    server 192.168.1.10:8080 weight=5;
    server 192.168.1.11:8080 weight=5;
    server 192.168.1.12:8080 backup;  # 备用服务器
    
    # 会话保持(IP哈希)
    ip_hash;
    
    # 最少连接
    least_conn;
    
    # 健康检查
    server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
}

server {
    location / {
        proxy_pass http://backend_servers;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
WebSocket代理
支持WebSocket长连接代理
location /ws/ {
    proxy_pass http://backend_server;
    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_read_timeout 86400;  # WebSocket长连接超时时间
}
SSL/HTTPS 配置
基础SSL配置
配置HTTPS证书和密钥
server {
    listen 443 ssl http2;
    server_name example.com;
    
    # SSL证书路径
    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加密套件
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers on;
    
    # SSL会话缓存
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
}
HTTP自动跳转HTTPS
将HTTP请求自动重定向到HTTPS
server {
    listen 80;
    server_name example.com;
    # 所有HTTP请求301跳转到HTTPS
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com;
    # SSL配置...
}
Let's Encrypt证书
免费SSL证书配置
server {
    listen 443 ssl http2;
    server_name example.com;
    
    # Let's Encrypt证书路径
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    
    # 包含推荐的SSL配置
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}

# ACME挑战验证(证书续期需要)
location /.well-known/acme-challenge/ {
    root /var/www/certbot;
}
Gzip压缩配置
启用Gzip压缩
压缩响应内容,减少传输大小,提升加载速度
# 开启gzip
gzip on;

# 压缩级别(1-9,数值越大压缩率越高但越耗CPU)
gzip_comp_level 6;

# 最小压缩文件大小
gzip_min_length 1k;

# 压缩缓冲区
gzip_buffers 4 16k;

# 压缩类型
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;

# 对代理请求也进行压缩
gzip_proxied any;

# 添加Vary头
gzip_vary on;

# 禁用IE6的gzip
gzip_disable "MSIE [1-6]\.";
缓存配置
静态文件缓存
为静态资源设置浏览器缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
    expires 30d;  # 缓存30天
    add_header Cache-Control "public, immutable";
    add_header Vary Accept-Encoding;
    access_log off;  # 关闭静态资源访问日志
}

# 不缓存HTML文件
location ~* \.html$ {
    expires -1;
    add_header Cache-Control "no-store, no-cache, must-revalidate";
}
代理缓存配置
配置Nginx代理缓存,减轻后端服务器压力
# 定义缓存区域
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;  # 200和302响应缓存10分钟
        proxy_cache_valid 404 1m;       # 404响应缓存1分钟
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        
        # 缓存键
        proxy_cache_key $scheme$proxy_host$request_uri;
        
        # 添加缓存状态头
        add_header X-Cache-Status $upstream_cache_status;
    }
}
日志配置
访问日志和错误日志
配置日志格式和存储路径
# 定义日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"';

# 访问日志
access_log /var/log/nginx/access.log main;

# 错误日志
error_log /var/log/nginx/error.log warn;

# 关闭特定location的访问日志
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    access_log off;
    expires 30d;
}
日志切割配置
使用logrotate进行日志切割
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily                    # 每天切割
    missingok                # 日志不存在不报错
    rotate 14                # 保留14天
    compress                 # 压缩旧日志
    delaycompress            # 延迟压缩
    notifempty               # 空日志不切割
    create 0640 www-data adm # 创建新日志文件权限
    sharedscripts            # 共享脚本
    postrotate
        # 发送信号重新打开日志文件
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}
安全配置
安全响应头
添加安全相关的HTTP响应头
server {
    # 隐藏Nginx版本号
    server_tokens off;
    
    # 防止点击劫持
    add_header X-Frame-Options "SAMEORIGIN" always;
    
    # XSS保护
    add_header X-XSS-Protection "1; mode=block" always;
    
    # 内容类型嗅探保护
    add_header X-Content-Type-Options "nosniff" always;
    
    # 引用策略
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
    # 内容安全策略
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';" always;
}
限流配置
限制请求速率,防止DDoS攻击
# 定义限流区域
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    location / {
        # 限流:每秒10个请求,突发20个
        limit_req zone=one burst=20 nodelay;
        
        # 连接限制:单个IP最多10个连接
        limit_conn addr 10;
        
        # 限流错误页面
        limit_req_status 429;
        limit_conn_status 503;
    }
    
    # 特定location不限流
    location /static/ {
        limit_req off;
        limit_conn off;
    }
}
IP黑名单
封禁特定IP地址
# 在http块中定义黑名单
geo $blocked_ip {
    default 0;
    192.168.1.100 1;  # 封禁单个IP
    10.0.0.0/24 1;    # 封禁IP段
}

server {
    location / {
        if ($blocked_ip) {
            return 403;
        }
        # ...
    }
    
    # 或使用allow/deny
    location /admin/ {
        allow 192.168.1.0/24;  # 允许内网
        deny all;              # 拒绝其他所有IP
    }
}