Nginx 安装与基础配置
一键安装 Nginx 并设为开机自启,附最简反向代理配置与防火墙放行。
适用系统UbuntuDebianCentOS需要 root / sudo
功能简介
- 安装 Nginx 并设为开机自启
- 提供一个最简「反向代理到本地服务」的配置示例
- 提示防火墙放行与配置测试方法
一键执行命令
bash
# Ubuntu / Debian
sudo apt update && sudo apt install -y nginx
sudo systemctl enable --now nginxbash
# CentOS / Rocky / Alma
sudo dnf install -y nginx
sudo systemctl enable --now nginx记得在 防火墙 放行 HTTP/HTTPS:
bash
sudo ufw allow 80,443/tcp # ufw(Ubuntu/Debian)
# 或 firewalld(CentOS):
# sudo firewall-cmd --permanent --add-service=http --add-service=https && sudo firewall-cmd --reload验证安装
bash
nginx -v
systemctl status nginx --no-pager
curl -I http://localhost # 应返回 200 与 Server: nginx浏览器访问 http://服务器IP 看到默认欢迎页即成功。
最简反向代理示例
把对 80 端口的请求转发到本机 3000 端口的应用(如 Node 服务):
bash
sudo tee /etc/nginx/conf.d/app.conf <<'EOF'
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
EOF
# 测试配置语法再重载(强烈建议每次改完都先 -t)
sudo nginx -t && sudo systemctl reload nginx注意事项
- ⚠️ 改完配置务必先
sudo nginx -t检查语法,通过后再reload,避免把正在运行的服务搞挂。 - Ubuntu/Debian 习惯把站点配置放在
/etc/nginx/sites-available/并软链到sites-enabled/;用conf.d/*.conf同样有效,二选一即可。
回滚 / 卸载方案
bash
# Ubuntu / Debian
sudo systemctl disable --now nginx
sudo apt purge -y nginx nginx-common && sudo apt autoremove -y