参考资料

  1. Nginx设置配置文件详细说明以及案例
  2. 查看nginx 配置文件路径查找
  3. nginx 配置ssl
  4. Nginx配置修改工具Ansible详细说明以及案例
  5. nginx配置文件详解
  6. 如何查看nginx主配置文件路径方式
  7. SCGI(Simple Common Gateway Interface,简单通用网关接口)详细说明以及案例
  8. Nginx配置详细说明以及案例

Nginx 监控与响应设置(含示例)

1. 安装 Nginx(若未安装)

# Ubuntu/Debian
sudo apt update && sudo apt install nginx

# CentOS/RHEL
sudo yum install epel-release && sudo yum install nginx

2. 配置 Nginx 监控

(1) 启用访问日志 & 错误日志

修改 /etc/nginx/nginx.conf

http {
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log warn;
}

日志轮转(logrotate

sudo nano /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        /usr/sbin/nginx -s reload
    endscript
}
(2) 启用 Nginx 状态监控(stub_status

修改 /etc/nginx/conf.d/status.conf

server {
    listen 127.0.0.1:8080;
    location /nginx_status {
        stub_status on;
        allow 127.0.0.1;  # 仅允许本地访问
        deny all;
    }
}

测试状态接口

curl http://127.0.0.1:8080/nginx_status

输出示例

Active connections: 3
server accepts handled requests
 100 100 200
Reading: 0 Writing: 1 Waiting: 2

3. 使用 Prometheus + Grafana 监控

(1) 安装 nginx-prometheus-exporter
wget https://github.com/nginxinc/nginx-prometheus-exporter/releases/download/v0.11.0/nginx-prometheus-exporter_0.11.0_linux_amd64.tar.gz
tar -xzf nginx-prometheus-exporter_*.tar.gz
sudo mv nginx-prometheus-exporter /usr/local/bin/
(2) 启动 Exporter
sudo /usr/local/bin/nginx-prometheus-exporter -nginx.scrape-uri=http://127.0.0.1:8080/nginx_status

验证

curl http://localhost:9113/metrics

输出示例

nginx_connections_accepted 100
nginx_connections_active 3
(3) 配置 Prometheus(/etc/prometheus/prometheus.yml
scrape_configs:
  - job_name: 'nginx'
    static_configs:
      - targets: ['localhost:9113']

重启 Prometheus

sudo systemctl restart prometheus
(4) Grafana 仪表盘
  • 导入 Nginx 仪表盘(ID: 14515

  • 访问 http://<grafana-server>:3000 查看监控


4. 配置 Nginx 响应策略

(1) 限流(Rate Limiting)

修改 /etc/nginx/nginx.conf

http {
    limit_req_zone $binary_remote_addr zone=limit_zone:10m rate=10r/s;

    server {
        location /api/ {
            limit_req zone=limit_zone burst=20 nodelay;
            proxy_pass http://backend;
        }
    }
}

测试限流

ab -n 100 -c 10 http://your-server/api/
(2) 缓存(Cache)

修改 /etc/nginx/nginx.conf

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;

server {
    location /static/ {
        proxy_cache my_cache;
        proxy_pass http://backend;
    }
}
(3) 负载均衡(Load Balancing)
upstream backend {
    server 192.168.1.10:8080 weight=2;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080 backup;
}

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