Nginx配置与优化

概述

Nginx Web服务器配置、优化和SSL证书集成指南。

适用版本:Nginx 1.25.1 及以上。

基础配置

基本服务器配置

# /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
 
events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}
 
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" "$http_x_forwarded_for"';
 
    access_log /var/log/nginx/access.log main;
 
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
 
    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
 
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

SSL证书配置

Certbot生成的证书配置

# /etc/nginx/sites-available/example.com
server {
    listen 80;
    server_name example.com www.example.com;
 
    # 重定向HTTP到HTTPS
    return 301 https://$server_name$request_uri;
}
 
server {
    listen 443 ssl;
    http2 on;
    server_name example.com www.example.com;
 
    # SSL证书路径(Certbot生成)
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
 
    # SSL优化配置
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;
 
    # HSTS头
    add_header Strict-Transport-Security "max-age=63072000" always;
 
    # 根目录配置
    root /var/www/example.com;
    index index.html index.htm;
 
    location / {
        try_files $uri $uri/ =404;
    }
 
    # 静态文件缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
 
    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
    }
}

多域名SSL配置

server {
    listen 443 ssl;
    http2 on;
    server_name example.com www.example.com api.example.com;
 
    # 使用通配符证书
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
 
    # 根据不同子域名路由
    location / {
        if ($host = 'api.example.com') {
            proxy_pass http://localhost:3000;
        }
        if ($host = 'www.example.com') {
            root /var/www/example.com;
        }
    }
}

反向代理配置

基本反向代理

server {
    listen 80;
    server_name app.example.com;
 
    location / {
        proxy_pass http://localhost: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;
 
        # WebSocket支持
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

负载均衡配置

upstream backend {
    least_conn;
    server backend1.example.com:8080;
    server backend2.example.com:8080;
    server backend3.example.com:8080 backup;
}
 
server {
    listen 80;
    server_name loadbalancer.example.com;
 
    location / {
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

性能优化

缓存配置

# 代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m;
 
server {
    location / {
        proxy_cache my_cache;
        proxy_cache_key "$scheme$request_method$host$request_uri";
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        add_header X-Cache-Status $upstream_cache_status;
    }
}

连接优化

# TCP优化
tcp_nopush on;
tcp_nodelay on;
sendfile on;
sendfile_max_chunk 512k;
 
# 连接限制
limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_conn addr 100;
 
# 请求限制
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
limit_req zone=one burst=20 nodelay;

安全配置

基础安全头

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self';" always;

限制访问

# 禁止特定User-Agent
if ($http_user_agent ~* (wget|curl|libwww-perl|python|nikto|sqlmap)) {
    return 403;
}
 
# IP白名单
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;

日志管理

自定义日志格式

log_format detailed '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    'rt=$request_time uct="$upstream_connect_time" '
                    'uht="$upstream_header_time" urt="$upstream_response_time"';
 
# 按域名分离日志
access_log /var/log/nginx/example.com.access.log detailed;
error_log /var/log/nginx/example.com.error.log warn;

日志轮转

# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 nginx adm
    sharedscripts
    postrotate
        /usr/sbin/nginx -s reopen
    endscript
}

与Certbot集成

自动证书更新后重载Nginx

# 创建Certbot更新后钩子脚本
vim /etc/letsencrypt/renewal-hooks/post/reload-nginx.sh
 
#!/bin/bash
# 证书更新后重载Nginx
systemctl reload nginx
 
chmod +x /etc/letsencrypt/renewal-hooks/post/reload-nginx.sh

Docker环境中的Nginx+Certbot集成

在宿主机运行 Certbot,并仅在证书成功续期后测试和重载 Nginx:

certbot renew --deploy-hook "nginx -t && nginx -s reload"

故障排除

常见问题

  1. 证书路径错误

    # 检查证书路径
    ls -la /etc/letsencrypt/live/example.com/
    # 测试Nginx配置
    nginx -t
  2. 权限问题

    # 确保Nginx用户有读取权限
    chmod 755 /etc/letsencrypt/live/
    chmod 644 /etc/letsencrypt/live/example.com/*.pem
    chmod 600 /etc/letsencrypt/live/example.com/privkey.pem
  3. 配置测试

    # 测试Nginx配置
    nginx -t
    # 重载配置
    nginx -s reload
    # 或
    systemctl reload nginx

监控与维护

状态检查

# 检查Nginx状态
systemctl status nginx
# 查看连接数
netstat -an | grep :443 | wc -l
# 查看错误日志
tail -f /var/log/nginx/error.log

性能监控

# 实时监控
nginx -T  # 显示完整配置
# 使用ngxtop监控
ngxtop -l /var/log/nginx/access.log

Obsidian关联

相关笔记

反向链接

知识图谱

Nginx配置
├── SSL证书配置
│   ├── 引用自: [[Docker使用Certbot颁发更新证书#证书文件结构|证书文件结构]]
│   └── 配置示例: ssl_certificate /etc/letsencrypt/live/...
├── 性能优化
│   ├── 缓存配置
│   └── 连接优化
└── 安全配置
    ├── 安全头设置
    └── 访问限制

集成工作流

  1. 证书生成:使用Docker使用Certbot颁发更新证书自动化生成SSL证书
  2. Nginx配置:在此笔记中配置证书路径和SSL参数
  3. 自动化更新:Certbot更新证书后自动重载Nginx配置
  4. 监控维护:监控SSL证书状态和Nginx性能

快速参考

  • 证书路径/etc/letsencrypt/live/域名/ (来自Docker使用Certbot颁发更新证书)
  • 配置测试nginx -t
  • 重载配置nginx -s reloadsystemctl reload nginx
  • 证书更新钩子/etc/letsencrypt/renewal-hooks/post/