Nginx 作为一款高性能的 Web 服务器和反向代理工具,以下是其常用操作和命令的整理,涵盖安装、配置、管理等场景:
# 安装
sudo apt update
sudo apt install nginx
# 卸载(保留配置文件)
sudo apt remove nginx
# 完全卸载(删除配置文件)
sudo apt purge nginx
# 添加EPEL仓库后安装
sudo yum install epel-release
sudo yum install nginx
# 卸载
sudo yum remove nginx
# 启动
sudo systemctl start nginx
# 停止
sudo systemctl stop nginx
# 重启(平滑重启,不中断连接)
sudo systemctl reload nginx
# 强制重启(中断连接)
sudo systemctl restart nginx
# 查看状态
sudo systemctl status nginx
# 设置开机自启
sudo systemctl enable nginx
/etc/nginx/nginx.conf
/etc/nginx/conf.d/
或 /etc/nginx/sites-available/
/var/www/html/
/var/log/nginx/access.log
和 error.log
# 测试配置文件语法
sudo nginx -t
# 显示Nginx版本和编译参数
nginx -V
# 重新加载配置(不重启服务)
sudo nginx -s reload
bash
sudo nano /etc/nginx/conf.d/example.com.conf
示例配置
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
bash
sudo nginx -t && sudo systemctl reload nginx
# 实时查看访问日志
tail -f /var/log/nginx/access.log
# 按日期切割日志(需配置cron任务)
sudo mv /var/log/nginx/access.log /var/log/nginx/access-$(date +%Y%m%d).log
sudo nginx -s reopen # 重新打开日志文件
# 查看活跃连接数
netstat -anp | grep nginx | grep ESTABLISHED | wc -l
http {
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
limit_conn conn_limit 100; # 每个IP限制100个连接
}
}
bash
sudo apt install certbot python3-certbot-nginx
bash
sudo certbot --nginx -d example.com -d www.example.com
bash
sudo certbot renew --dry-run
bash
sudo lsof -i :80 # 检查80端口占用
bash
sudo chown -R www-data:www-data /var/www/ # 修正目录权限
root
路径是否正确。index
文件存在。nginx
location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
}
nginx
upstream backend {
server 10.0.0.1;
server 10.0.0.2;
}
掌握这些操作后,可以覆盖 Nginx 的日常管理需求。遇到复杂场景时,建议结合官方文档(nginx.org)进一步研究。