插件窝 干货文章 Nginx定时巡检与瘦身实践

Nginx定时巡检与瘦身实践

Nginx 巡检 echo LOG 930    来源:    2025-04-20

Nginx定时巡检与瘦身实践

一、Nginx巡检方案

1. 定时巡检脚本

#!/bin/bash

# Nginx巡检脚本
LOG_FILE="/var/log/nginx_inspection_$(date +%Y%m%d).log"

{
    echo "====== Nginx巡检报告 ======"
    echo "巡检时间: $(date)"
    echo ""

    # 1. 检查Nginx进程状态
    echo "=== 进程状态 ==="
    ps aux | grep nginx | grep -v grep
    echo ""

    # 2. 检查Nginx版本
    echo "=== 版本信息 ==="
    nginx -v 2>&1
    echo ""

    # 3. 检查配置文件语法
    echo "=== 配置检查 ==="
    nginx -t 2>&1
    echo ""

    # 4. 检查监听端口
    echo "=== 监听端口 ==="
    netstat -tulnp | grep nginx
    echo ""

    # 5. 检查错误日志最后20条
    echo "=== 错误日志 ==="
    tail -n 20 /var/log/nginx/error.log
    echo ""

    # 6. 检查访问量统计
    echo "=== 访问统计 ==="
    echo "总连接数: $(netstat -an | grep ':80' | wc -l)"
    echo "活跃连接: $(netstat -an | grep ':80' | grep ESTABLISHED | wc -l)"
    echo ""

    # 7. 检查系统资源占用
    echo "=== 资源占用 ==="
    top -bn1 | grep nginx
    echo ""

} > $LOG_FILE

echo "巡检完成,日志已保存至: $LOG_FILE"

2. 定时任务设置

# 每天凌晨2点执行巡检
0 2 * * * /path/to/nginx_inspection.sh

二、Nginx配置瘦身实践

1. 精简主配置文件

优化后的nginx.conf示例:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
    multi_accept on;
    use epoll;
}

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 buffer=32k flush=5m;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    server_tokens off;

    # 包含各个站点的独立配置
    include /etc/nginx/conf.d/*.conf;
}

2. 优化服务器配置

server {
    listen 80;
    server_name example.com;

    root /var/www/html;
    index index.html;

    # 禁用不必要的方法
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }

    # 安全头设置
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    add_header X-XSS-Protection "1; mode=block";

    # 静态资源缓存
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 30d;
        access_log off;
        add_header Cache-Control "public";
    }

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

    # 错误页面
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

3. 日志瘦身方案

# 1. 按天分割日志
map $time_iso8601 $logdate {
    '~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
    default 'nodate';
}

access_log /var/log/nginx/access-$logdate.log main buffer=32k flush=5m;

# 2. 日志轮转配置 (/etc/logrotate.d/nginx)
/var/log/nginx/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 0640 nginx adm
    sharedscripts
    postrotate
        /bin/kill -USR1 `cat /var/run/nginx.pid 2>/dev/null` 2>/dev/null || true
    endscript
}

三、性能优化参数

1. 系统内核参数优化

# /etc/sysctl.conf 添加以下内容
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 0  # 在NAT环境下建议关闭
net.ipv4.tcp_fin_timeout = 30
fs.file-max = 999999

2. Nginx性能参数

# 在events模块中
events {
    worker_connections 65535;
    multi_accept on;
    use epoll;
}

# 在http模块中
http {
    # 开启高效文件传输模式
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    # 连接超时时间
    keepalive_timeout 65;
    keepalive_requests 1000;

    # 客户端请求体大小限制
    client_max_body_size 10m;
    client_body_buffer_size 128k;

    # 缓冲区优化
    client_header_buffer_size 4k;
    large_client_header_buffers 4 16k;

    # 开启Gzip压缩
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 2;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_vary on;
    gzip_disable "MSIE [1-6]\.";
}

四、安全加固措施

1. 禁用不必要的信息

server {
    # 隐藏Nginx版本号
    server_tokens off;

    # 禁用自动目录列表
    autoindex off;

    # 限制HTTP方法
    if ($request_method !~ ^(GET|HEAD|POST)$ ) {
        return 405;
    }
}

2. 安全头设置

add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "no-referrer-when-downgrade";
add_header Content-Security-Policy "default-src 'self'";

3. 限制访问

# 限制IP访问频率
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

location / {
    limit_req zone=one burst=20 nodelay;
}

# 限制并发连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;

location /download/ {
    limit_conn addr 5;
}

五、自动化维护工具

1. 使用goaccess分析日志

# 实时分析访问日志
goaccess /var/log/nginx/access.log -o /var/www/html/report.html --real-time-html

2. 使用certbot自动续期SSL证书

# 安装certbot
apt install certbot python3-certbot-nginx

# 设置自动续期
certbot renew --dry-run

# 添加到crontab
0 0,12 * * * /usr/bin/certbot renew --quiet

通过以上定时巡检和瘦身实践,可以确保Nginx服务器保持最佳性能和安全状态,同时减少不必要的资源消耗。