Linux部署Nginx核心三步:安装(按发行版选apt/yum/dnf)、启动并验证(systemctl启服务+nginx -t检查+访问欢迎页)、配置反向代理(conf.d下建独立配置+proxy_pass转发+reload生效)。

Linux上部署Nginx,核心就三步:安装、启动并验证、配置反向代理。只要系统是主流发行版(如CentOS 7+/8、Ubuntu 20.04+),操作基本一致,关键在细节别出错。
一、安装Nginx(按系统选命令)
推荐用系统包管理器安装,稳定且自动处理依赖:
- Ubuntu/Debian:运行 sudo apt update && sudo apt install nginx
- CentOS 7/8 或 Rocky/AlmaLinux:先启用 EPEL 源(sudo yum install epel-release 或 sudo dnf install epel-release),再执行 sudo yum install nginx(CentOS 7)或 sudo dnf install nginx(CentOS 8+)
装完不急着启动,先检查是否成功:nginx -v 查版本,which nginx 看路径(通常是 /usr/sbin/nginx)。
二、启动服务并确认能访问
启动前建议先测试配置语法:sudo nginx -t,输出 “syntax is ok” 和 “test is successful” 才安全。
- Ubuntu/Debian:用 systemd 启动:sudo systemctl start nginx,设开机自启:sudo systemctl enable nginx
- CentOS/Rocky:命令相同:sudo systemctl start nginx 和 sudo systemctl enable nginx
打开浏览器访问服务器 IP(如 http://192.168.1.100),看到 “Welcome to nginx!” 页面,说明服务已正常运行。注意关闭防火墙或放行端口:sudo ufw allow 'Nginx Full'(Ubuntu)或 sudo firewall-cmd --permanent --add-service=http(CentOS),然后重载规则。
三、配置反向代理(以代理本地8080端口的Web应用为例)
编辑主配置文件:sudo nano /etc/nginx/nginx.conf,但更推荐在 /etc/nginx/conf.d/ 下新建独立配置,比如 myapp.conf,避免误改全局配置。
内容示例如下(替换 your_domain_or_ip 为实际域名或IP):
server {
listen 80;
server_name your_domain_or_ip;
location / {
proxy_pass http://127.0.0.1:8080;
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;
}
}
保存后,再次运行 sudo nginx -t 测试语法,没问题就重载配置:sudo systemctl reload nginx(比 restart 更轻量)。
此时访问该域名或IP,请求就会被转发到本机的 8080 端口服务(如 Spring Boot、Node.js 应用等)。
四、常见问题快速排查
- 502 Bad Gateway:多半是 proxy_pass 指向的服务没起来,或端口不对;先 curl http://127.0.0.1:8080 确认后端能通
- 403 Forbidden:检查 Nginx 工作用户(user 指令)是否有权限读取静态文件目录,或 SELinux 是否拦截(CentOS 可临时 setenforce 0 测试)
- 配置不生效:确认 conf 文件在 include /etc/nginx/conf.d/*.conf; 路径下被加载,且文件名以 .conf 结尾
基本上就这些。不复杂但容易忽略语法检查和权限细节,动手前多敲两遍 nginx -t,省一半排错时间。










