插件窝 干货文章 Nginx常用配置与技巧有哪些

Nginx常用配置与技巧有哪些

Nginx proxy location 配置 417    来源:    2025-04-27

Nginx作为高性能的Web服务器和反向代理工具,其配置灵活性是关键优势。以下整理出实用配置与技巧,涵盖常见场景和优化方向:


一、核心配置模板

# 全局配置
user nginx;
worker_processes auto;  # 自动匹配CPU核心数
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;  # 单个worker最大连接数
    use epoll;  # Linux高性能事件模型
    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;

    # Gzip压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript;

    include /etc/nginx/conf.d/*.conf;  # 加载子配置文件
}

二、高频实用配置

1. 静态文件服务

server {
    listen 80;
    server_name example.com;
    root /var/www/html;

    location / {
        try_files $uri $uri/ =404;
        expires 30d;  # 缓存控制
        access_log off;  # 静态资源可关闭日志
    }

    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
    }
}

2. 反向代理

location /api/ {
    proxy_pass http://backend_server;
    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_connect_timeout 60s;
    proxy_read_timeout 60s;
}

3. 负载均衡

upstream backend {
    least_conn;  # 最少连接算法
    server 10.0.0.1:8080 weight=3;  # 权重
    server 10.0.0.2:8080;
    server 10.0.0.3:8080 backup;  # 备用服务器
}

server {
    location / {
        proxy_pass http://backend;
    }
}

4. HTTPS配置

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    # 强制HTTPS跳转
    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    }
}

5. 限制访问

# IP白名单
location /admin/ {
    allow 192.168.1.0/24;
    allow 10.0.0.1;
    deny all;
}

# 速率限制(每秒1请求)
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
location /login/ {
    limit_req zone=one burst=5;
}

三、性能优化技巧

  1. Worker配置

    worker_processes auto;  # 自动匹配CPU核心
    worker_rlimit_nofile 100000;  # 提高文件描述符限制
    
  2. 缓存优化

    proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
    location / {
       proxy_cache my_cache;
       proxy_cache_valid 200 302 10m;
    }
    
  3. 长连接复用

    upstream backend {
       keepalive 32;  # 连接池大小
    }
    
  4. 日志优化

    • 关闭静态资源日志:access_log off;
    • 异步日志写入:access_log /path/to/log combined buffer=32k flush=5s;

四、调试与问题排查

  1. 日志分析工具

    • 实时监控:tail -f /var/log/nginx/access.log | grep "500"
    • 统计高频IP:awk '{print $1}' access.log | sort | uniq -c | sort -nr
  2. 状态监控

    location /nginx_status {
       stub_status on;
       allow 127.0.0.1;
       deny all;
    }
    

    输出示例:

    Active connections: 3 
    server accepts handled requests
    100 100 200 
    Reading: 0 Writing: 1 Waiting: 2
    
  3. 重定向测试

    curl -I http://example.com  # 检查HTTP头
    nginx -t  # 测试配置语法
    

五、高级技巧

  1. WebSocket代理

    location /ws/ {
       proxy_pass http://backend;
       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection "upgrade";
    }
    
  2. GeoIP模块

    geoip_country /usr/share/GeoIP/GeoIP.dat;
    location / {
       if ($geoip_country_code = CN) { return 403; }
    }
    
  3. A/B测试

    split_clients "${remote_addr}AAA" $variant {
       50%   "/var/www/v1";
       50%   "/var/www/v2";
    }
    

常见问题解决

  • 502 Bad Gateway:检查后端服务是否存活,调整proxy_read_timeout
  • 地址重写冲突:使用rewrite时注意lastbreak的区别。
  • 证书过期:设置crontab自动续期(如Certbot)。

通过合理组合这些配置,可以构建高性能、安全的Nginx服务。建议根据实际需求逐步调整参数,并通过压测工具(如ab、wrk)验证效果。