一、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;
}
四、安全配置
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