Nginx-full 安装与卸载指南 🚀

本指南详细介绍了 Nginx Web 服务器的完整生命周期管理,包括安装、配置优化、日常维护、故障排除以及完全卸载。
nginx-full
版本包含 http_dav_module
模块,适合搭建 WebDAV 服务
✨ 目录
🌟 Nginx 简介
Nginx (发音为 “engine-x”) 是一个高性能的 HTTP 和反向代理服务器,以其稳定性、丰富的功能集、简单的配置文件和低资源消耗而闻名。它由 Igor Sysoev 创建,最初是为俄罗斯的大型网站 Rambler.ru 开发的。
🎯 Nginx 主要特性:
- 高性能: 事件驱动的异步架构,能够处理大量并发连接
- 负载均衡: 内置多种负载均衡算法
- 反向代理: 强大的反向代理功能
- 缓存加速: 静态内容缓存和动态内容加速
- 高可靠性: 极低的故障率和强大的故障转移能力
- 模块化设计: 丰富的模块生态系统
📊 Nginx 与 Apache 对比:
特性 |
Nginx |
Apache |
架构 |
事件驱动 |
进程/线程驱动 |
内存使用 |
较低 |
较高 |
并发处理 |
优秀 |
良好 |
静态内容 |
极快 |
快 |
动态内容 |
通过 FastCGI |
原生支持 |
配置语法 |
简洁 |
较复杂 |
📦 一、Nginx 安装指南
1️⃣ Ubuntu/Debian 系统的安装方法
Ubuntu/Debian 系统
1 2 3 4 5
| sudo apt update
sudo apt install nginx-full -y
|
从源码编译安装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| sudo apt install build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev -y
wget http://nginx.org/download/nginx-1.24.0.tar.gz tar -zxvf nginx-1.24.0.tar.gz cd nginx-1.24.0
./configure \ --prefix=/usr/local/nginx \ --with-http_ssl_module \ --with-http_v2_module \ --with-http_stub_status_module \ --with-http_gzip_static_module \ --with-http_dav_module
make sudo make install
|
2️⃣ 验证安装
1 2 3 4 5 6 7 8 9
| nginx -v
nginx -V
which nginx whereis nginx
|
3️⃣ 服务管理
1 2 3 4 5 6 7 8 9 10 11
| sudo systemctl start nginx
sudo systemctl status nginx
sudo systemctl enable nginx
sudo systemctl daemon-reload
|
4️⃣ 防火墙配置
1 2 3 4 5 6 7 8
| sudo ufw allow 'Nginx Full'
sudo ufw allow 80/tcp sudo ufw allow 443/tcp
sudo ufw status
|
5️⃣ 验证安装成功
1 2 3 4 5 6 7 8 9
| ps aux | grep nginx
sudo netstat -tulnp | grep :80 sudo ss -tulnp | grep :80
curl -I http://localhost
|
6️⃣ 升级 Nginx
1 2 3 4 5
| sudo apt update && sudo apt upgrade nginx -y
sudo systemctl restart nginx
|
⚙️ 二、Nginx 维护命令
1️⃣ 服务管理命令
命令 |
说明 |
使用场景 |
sudo systemctl start nginx |
启动 Nginx 服务 |
初次安装后 |
sudo systemctl stop nginx |
停止 Nginx 服务 |
维护前 |
sudo systemctl restart nginx |
重启 Nginx 服务 |
配置更改后 |
sudo systemctl reload nginx |
重载配置(不中断服务) |
修改配置后 |
sudo systemctl status nginx |
查看服务状态 |
日常检查 |
sudo systemctl enable nginx |
设置开机自启 |
系统启动配置 |
sudo systemctl disable nginx |
禁用开机自启 |
临时禁用 |
2️⃣ 配置检查与验证
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| sudo nginx -t
sudo nginx -t -c /etc/nginx/nginx.conf
sudo nginx -T
nginx -V 2>&1 | grep -- '--with-'
sudo nginx -T | grep -E "^(http|server|location)"
|
3️⃣ 进程管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| sudo nginx -s quit
sudo nginx -s stop
sudo nginx -s reload
sudo nginx -s reopen
cat /var/run/nginx.pid
ps aux | grep nginx pgrep -lf nginx
|
4️⃣ 日志管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| sudo tail -f /var/log/nginx/error.log
sudo tail -f /var/log/nginx/access.log
sudo grep "25/May/2023" /var/log/nginx/access.log
sudo journalctl -u nginx --since today sudo journalctl -u nginx --since "2023-05-25" --until "2023-05-26"
sudo nano /etc/logrotate.d/nginx
sudo logrotate -f /etc/logrotate.d/nginx
|
5️⃣ 系统检查与监控
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| sudo systemctl is-enabled nginx
sudo netstat -tulnp | grep :80 sudo ss -tulnp | grep :80 sudo lsof -i :80
sudo find /etc/nginx -name "*.conf" -exec nginx -t -c {} \;
source ~/.bashrc
df -h /var/log/nginx/
|
6️⃣ 连接和性能检查
1 2 3 4 5 6 7 8 9 10 11
| netstat -an | grep :80 | wc -l
curl http://localhost/nginx_status
sudo watch -n 1 "ps aux --sort=-%cpu | grep nginx"
sudo watch -n 1 "free -h && echo '---' && ps aux --sort=-%mem | head -10"
|
🗑️ 三、Nginx 卸载指南
1️⃣ 不同系统的卸载方法
Ubuntu/Debian 系统
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| sudo systemctl stop nginx
sudo systemctl disable nginx
sudo apt remove nginx -y
sudo apt remove --purge nginx -y
sudo apt remove --purge nginx-full -y sudo apt autoremove --purge -y
|
CentOS/RHEL 系统
1 2 3 4 5 6 7 8 9 10 11 12
| sudo systemctl stop nginx
sudo systemctl disable nginx
sudo yum remove nginx -y
sudo rm -rf /etc/nginx sudo rm -rf /var/log/nginx
|
2️⃣ 清理残留文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| sudo rm -rf /etc/nginx/ sudo rm -rf /var/log/nginx/ sudo rm -rf /var/cache/nginx/
sudo rm -rf /var/www/html/
sudo rm -f /etc/init.d/nginx sudo rm -f /lib/systemd/system/nginx.service
sudo rm -f /usr/sbin/nginx
|
3️⃣ 源码安装的卸载
1 2 3 4 5 6 7
| cd /path/to/nginx/source sudo make uninstall
sudo rm -rf /usr/local/nginx sudo rm -f /usr/bin/nginx
|
4️⃣ 验证卸载结果
1 2 3 4 5 6 7 8 9
| which nginx nginx -v
ps aux | grep nginx
sudo netstat -tulnp | grep :80
|
5️⃣ 备份重要数据(卸载前)
1 2 3 4 5 6 7 8
| sudo tar -czf nginx-backup-$(date +%Y%m%d).tar.gz /etc/nginx/
sudo tar -czf website-backup-$(date +%Y%m%d).tar.gz /var/www/html/
sudo tar -czf nginx-logs-backup-$(date +%Y%m%d).tar.gz /var/log/nginx/
|
🔧 四、故障排除技巧
1️⃣ 端口冲突解决
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| sudo lsof -i :80 sudo netstat -tulnp | grep :80 sudo ss -tulnp | grep :80
sudo kill -9 <PID>
sudo pkill -9 nginx
sudo systemctl stop apache2 sudo systemctl stop lighttpd
|
2️⃣ 权限问题修复
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| sudo chown -R www-data:www-data /var/www/html sudo chmod -R 755 /var/www/html
sudo chown -R www-data:www-data /var/log/nginx sudo chmod -R 755 /var/log/nginx
sudo sestatus sudo setsebool -P httpd_can_network_connect 1
sudo aa-status
|
3️⃣ 配置错误调试
1 2 3 4 5 6 7 8 9 10 11
| sudo nginx -t 2>&1 | grep error
sudo grep -n "server_name" /etc/nginx/sites-enabled/*
sudo nginx -t 2>&1 | tee /tmp/nginx-test.log
sudo nginx -t -c /etc/nginx/nginx.conf --debug
|
4️⃣ 常见错误解决
502 Bad Gateway 错误
1 2 3 4 5 6 7 8 9 10
| sudo systemctl status php-fpm sudo systemctl status tomcat
ls -la /var/run/php/php-fpm.sock
|
403 Forbidden 错误
1 2 3 4 5 6 7 8
| ls -la /var/www/html/
ls -la /var/www/html/index.*
sudo ausearch -m avc --start recent
|
404 Not Found 错误
1 2 3 4 5 6 7 8
| sudo nginx -T | grep -A5 -B5 "root"
sudo find /var/www -name "index.*"
sudo nginx -T | grep -A3 -B3 "try_files"
|
5️⃣ 日志分析技巧
1 2 3 4 5 6 7 8 9 10 11
| sudo tail -f /var/log/nginx/error.log | grep -E "(error|emerg|crit)"
sudo awk '$9 >= 400 {print $0}' /var/log/nginx/access.log
sudo awk '$9 >= 400 {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr
sudo awk '{if ($NF > 5) print $0}' /var/log/nginx/access.log | sort -k10 -nr
|
🚀 五、性能优化建议
1️⃣ 工作进程优化
1 2 3 4 5 6 7 8 9 10
| worker_processes auto; worker_cpu_affinity auto; worker_rlimit_nofile 100000;
events { worker_connections 4096; multi_accept on; use epoll; }
|
2️⃣ 缓冲区和超时优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| http { client_body_buffer_size 128k; client_max_body_size 20m; client_header_buffer_size 1k; large_client_header_buffers 4 4k; client_body_timeout 12; client_header_timeout 12; keepalive_timeout 15; send_timeout 10; sendfile on; tcp_nopush on; tcp_nodelay on; }
|
3️⃣ 启用 Gzip 压缩
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| gzip on; gzip_vary on; gzip_min_length 1024; gzip_proxied any; gzip_comp_level 6; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/atom+xml image/svg+xml;
|
4️⃣ 配置缓存策略
1 2 3 4 5 6 7 8 9 10 11 12 13
| location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; add_header Cache-Control "public, immutable"; add_header Pragma "public"; add_header Vary "Accept-Encoding"; }
location ~* \.(php|cgi|pl|py)$ { expires off; add_header Cache-Control "no-store, no-cache, must-revalidate"; }
|
5️⃣ 连接限制和请求频率控制
1 2 3 4 5 6 7 8 9 10 11
| limit_conn_zone $binary_remote_addr zone=addr:10m; limit_conn addr 100;
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
location /api/ { limit_req zone=one burst=20 nodelay; proxy_pass http://backend; }
|
6️⃣ 内核参数优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| echo ' # 最大文件描述符 fs.file-max = 1000000
# TCP优化 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 net.ipv4.tcp_fin_timeout = 30 net.ipv4.tcp_keepalive_time = 1200
# 内存优化 net.core.rmem_max = 16777216 net.core.wmem_max = 16777216 net.ipv4.tcp_rmem = 4096 87380 16777216 net.ipv4.tcp_wmem = 4096 65536 16777216 ' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
|
📊 六、监控与统计
1️⃣ 实时监控命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| sudo ngxtop
watch -n 1 "echo '当前连接数:' && netstat -an | grep :80 | wc -l"
sudo htop -p $(pgrep nginx | tr '\n' ',')
sudo tail -f /var/log/nginx/access.log | awk ' { print strftime("%Y-%m-%d %H:%M:%S"), $1, $7, $9, $NF "s" }'
|
2️⃣ 性能统计和分析
1 2 3 4 5 6 7 8 9 10 11
| sudo ps aux --sort=-%cpu | grep nginx
sudo pmap $(pgrep nginx | head -1) | tail -1
vmstat 1 10
iostat -dx 1
|
3️⃣ 启用状态监控模块
1 2 3 4 5 6 7 8 9 10 11 12
| server { listen 80; server_name localhost; location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; } }
|
4️⃣ 使用第三方监控工具
1 2 3 4 5 6 7 8 9 10 11
| sudo apt install goaccess -y
goaccess /var/log/nginx/access.log -o /var/www/html/report.html --real-time-html
sudo iftop -P -i eth0
sudo nethogs eth0
|
5️⃣ 日志分析脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| #!/bin/bash
LOG_FILE="/var/log/nginx/access.log"
echo "=== Nginx 访问日志分析 ===" echo "分析时间: $(date)" echo "日志文件: $LOG_FILE" echo ""
TOTAL_REQUESTS=$(wc -l < "$LOG_FILE") echo "总请求数: $TOTAL_REQUESTS"
SUCCESS_REQUESTS=$(awk '$9 ~ /^[23][0-9][0-9]$/ {count++} END {print count}' "$LOG_FILE") SUCCESS_RATE=$(echo "scale=2; $SUCCESS_REQUESTS * 100 / $TOTAL_REQUESTS" | bc) echo "成功请求率: $SUCCESS_RATE%"
ERROR_REQUESTS=$(awk '$9 ~ /^[45][0-9][0-9]$/ {count++} END {print count}' "$LOG_FILE") ERROR_RATE=$(echo "scale=2; $ERROR_REQUESTS * 100 / $TOTAL_REQUESTS" | bc) echo "错误请求率: $ERROR_RATE%"
echo "" echo "前10个最频繁访问的IP:" awk '{print $1}' "$LOG_FILE" | sort | uniq -c | sort -nr | head -10
echo "" echo "前10个最受欢迎的页面:" awk '{print $7}' "$LOG_FILE" | sort | uniq -c | sort -nr | head -10
|
🛡️ 七、安全最佳实践
1️⃣ 基础安全加固
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| server_tokens off;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
2️⃣ 访问控制和限制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 405; }
location ~ /\.(ht|git|svn) { deny all; return 404; }
location ~* \.(log|txt|conf|sql|bak)$ { deny all; return 403; }
|
3️⃣ SSL/TLS 安全配置
1 2 3 4 5 6 7 8
| ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384; ssl_prefer_server_ciphers on; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_session_tickets off; ssl_stapling on; ssl_stapling_verify on;
|
4️⃣ 防止常见攻击
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s; limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
set $block_sql_injections 0; if ($query_string ~ "union.*select.*\(") { set $block_sql_injections 1; } if ($block_sql_injections = 1) { return 403; }
if ($request_uri ~ "\.\./") { return 403; }
|
5️⃣ 安全头设置
1 2 3 4 5 6 7 8 9 10 11
| add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.example.com; style-src 'self' 'unsafe-inline' https://cdn.example.com;";
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()";
add_header Referrer-Policy "strict-origin-when-cross-origin";
add_header Feature-Policy "geolocation 'none'; microphone 'none'; camera 'none'";
|
6️⃣ 文件和目录权限
1 2 3 4 5 6 7 8 9 10 11 12
| sudo chown -R www-data:www-data /var/www/html sudo find /var/www/html -type d -exec chmod 755 {} \; sudo find /var/www/html -type f -exec chmod 644 {} \;
sudo chmod 600 /etc/nginx/nginx.conf sudo chmod 600 /etc/nginx/sites-available/*
sudo chmod 600 /etc/ssl/private/* sudo chmod 644 /etc/ssl/certs/*
|
💡 八、实用技巧
1️⃣ 快速测试配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| cat > test.conf << 'EOF' server { listen 8080; server_name test.local; return 200 "Test successful!\n"; } EOF
sudo nginx -t -c test.conf
sudo nginx -c $(pwd)/test.conf
sudo nginx -s stop -c $(pwd)/test.conf
|
2️⃣ 备份和版本控制
1 2 3 4 5 6 7 8 9 10 11 12
| sudo tar -czf nginx-backup-$(date +%Y%m%d).tar.gz /etc/nginx/
sudo mkdir /etc/nginx/.git sudo git -C /etc/nginx/ init sudo git -C /etc/nginx/ add . sudo git -C /etc/nginx/ commit -m "Initial nginx config"
sudo git -C /etc/nginx/ add . sudo git -C /etc/nginx/ commit -m "修改配置描述"
|
3️⃣ 批量操作和管理
1 2 3 4 5 6 7 8 9 10 11
| sudo find /etc/nginx/conf.d/ -name "*.conf" -exec sudo nginx -t -c {} \;
for config in /etc/nginx/sites-enabled/*; do echo "检查配置: $config" sudo nginx -t -c "$config" 2>&1 | grep -E "(error|emerg|crit)" done
sudo tar -czf nginx-config-$(date +%Y%m%d).tar.gz /etc/nginx/conf.d/ /etc/nginx/sites-available/ /etc/nginx/sites-enabled/
|
4️⃣ 性能测试工具
1 2 3 4 5 6 7 8 9 10 11
| sudo apt install apache2-utils -y
ab -n 1000 -c 100 http://localhost/
wrk -t12 -c400 -d30s http://localhost/
siege -c100 -t1M http://localhost/
|
5️⃣ 日志分析和监控
1 2 3 4 5 6 7 8 9 10 11
| sudo tail -f /var/log/nginx/error.log | grep -E --color=auto "(error|emerg|crit)"
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
awk '($NF > 5){print $7, $NF}' /var/log/nginx/access.log | sort -k2 -rn | head -20
goaccess /var/log/nginx/access.log -o /var/www/html/report.html --log-format=COMBINED
|
6️⃣ 自动化脚本示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| #!/bin/bash
case "$1" in start) sudo systemctl start nginx echo "Nginx started" ;; stop) sudo systemctl stop nginx echo "Nginx stopped" ;; restart) sudo systemctl restart nginx echo "Nginx restarted" ;; reload) sudo systemctl reload nginx echo "Nginx reloaded" ;; status) sudo systemctl status nginx ;; test) sudo nginx -t ;; monitor) watch -n 1 "echo '连接数:' && netstat -an | grep :80 | wc -l && echo '内存使用:' && ps aux | grep nginx | grep -v grep | awk '{print \$4}'" ;; *) echo "Usage: $0 {start|stop|restart|reload|status|test|monitor}" exit 1 ;; esac
|
7️⃣ Docker 容器化部署
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| docker run -d \ --name nginx \ -p 80:80 \ -p 443:443 \ -v /path/to/nginx.conf:/etc/nginx/nginx.conf \ -v /path/to/html:/usr/share/nginx/html \ nginx:latest
cat > docker-compose.yml << 'EOF' version: '3.8' services: nginx: image: nginx:latest ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/nginx.conf - ./html:/usr/share/nginx/html restart: unless-stopped EOF
|
通过这份完整的 Nginx 管理指南,您应该能够熟练地安装、配置、维护、优化和卸载 Nginx 服务器。记得在生产环境中操作前总是备份重要配置!🎯
📚 扩展资源
❓ 常见问题解答
Q: Nginx 和 Apache 哪个更好?
A: 这取决于具体需求。Nginx 更适合高并发场景,Apache 更适合需要大量模块的动态内容处理。
Q: 如何解决 502 Bad Gateway 错误?
A: 检查后端服务(如 PHP-FPM、Tomcat)是否正常运行,检查代理配置和超时设置。
Q: Nginx 性能优化的关键点是什么?
A: 工作进程数、连接数限制、缓冲区和缓存设置、Gzip 压缩、内核参数调优。
Q: 如何防止 DDoS 攻击?
A: 使用 limit_req 和 limit_conn 模块限制请求频率,配置防火墙规则,使用 Cloudflare 等 CDN 服务。
Q: SSL 证书配置要注意什么?
A: 使用强密码套件,启用 HSTS,配置 OCSP Stapling,定期更新证书。