Nginx 运维实战教程

官方终极手册:从零到生产级运维,群号 970360501

一、Nginx 安装指南:CentOS 与 Debian 全覆盖

CentOS

sudo yum install epel-release -y
sudo yum install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx

Debian / Ubuntu

sudo apt update
sudo apt install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx

二、Nginx 配置详解

基础配置

worker_processes auto;
events { worker_connections 1024; }
http {
    include mime.types;
    sendfile on;
    keepalive_timeout 65;
    server {
        listen 80;
        server_name localhost;
        location / { root html; index index.html; }
    }
}

虚拟主机

server {
    listen 80;
    server_name www.site.com;
    root /var/www/site;
    index index.html;
}

三、日志分析与性能优化

日志查看

tail -f /var/log/nginx/access.log
tail -n 50 /var/log/nginx/error.log

gzip 压缩

gzip on;
gzip_types text/plain text/css application/json;
gzip_min_length 1000;
gzip_comp_level 5;

缓存

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=STATIC:10m max_size=1g;
location ~* \.(jpg|png|css|js)$ {
    proxy_cache STATIC;
    expires 30d;
    add_header X-Cache $upstream_cache_status;
}

四、安全配置

HTTPS (Let's Encrypt)

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com

访问控制

location /admin {
    allow 192.168.1.0/24;
    deny all;
}

防 XSS/CSRF

add_header X-Frame-Options SAMEORIGIN;
add_header Content-Security-Policy "default-src 'self';"

五、监控与故障排查

一键诊断脚本

#!/bin/bash
echo "===== Nginx 状态 ====="
systemctl status nginx --no-pager
ss -tulnp | grep nginx
nginx -t
tail -n 20 /var/log/nginx/error.log

Prometheus 指标

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

六、常见问题 FAQ

  • 端口被占sudo lsof -i:80
  • 配置语法nginx -t
  • 备份文件cp nginx.conf{,.bak}
  • 更新版本sudo apt upgrade nginx