Linux安装Nginx推荐用包管理器:CentOS/RHEL执行yum或dnf install nginx,Ubuntu/Debian执行apt install nginx;安装后需systemctl start并enable服务,配置防火墙,验证80端口监听及首页访问,修改配置须nginx -t测试后reload。

Linux 上安装部署 Nginx 并不复杂,关键是选对方式、配好基础配置、确保服务能正常启停和响应请求。下面按实际操作逻辑分步说明,覆盖主流发行版(CentOS/RHEL 7+、Ubuntu/Debian)。
一、选择安装方式:包管理器 vs 源码编译
推荐优先使用系统包管理器安装,省心、安全、易更新;仅当需要特定模块(如 ngx_brotli)、最新版或深度定制时才考虑源码编译。
- CentOS/RHEL:执行 sudo yum install nginx(8+ 系统用 dnf install nginx)
- Ubuntu/Debian:执行 sudo apt update && sudo apt install nginx
- 安装后验证:nginx -v 查版本,systemctl status nginx 看是否已安装但未启动
二、启动并设为开机自启
Nginx 安装后默认不自动运行,需手动启用。
- 启动服务:sudo systemctl start nginx
- 设为开机自启:sudo systemctl enable nginx
- 检查监听状态:sudo ss -tlnp | grep :80(应看到 nginx 占用 80 端口)
- 打开防火墙(如启用):sudo firewall-cmd --permanent --add-service=http(CentOS)或 sudo ufw allow 'Nginx Full'(Ubuntu)
三、确认首页访问 & 基础配置路径
安装成功后,默认网页根目录是 /usr/share/nginx/html,主配置文件在 /etc/nginx/nginx.conf。
- 浏览器访问服务器 IP 或域名,应看到 “Welcome to nginx!” 页面
- 常用子配置目录:/etc/nginx/conf.d/(放 site 配置,如 default.conf 或 myapp.conf)
- 修改配置后务必测试:sudo nginx -t(语法检查),再重载:sudo systemctl reload nginx
四、简单反向代理示例(快速上手)
比如把 http://your-domain.com/api 转发到本地 3000 端口的服务:
- 在 /etc/nginx/conf.d/myapp.conf 中写入:
server {
listen 80;
server_name your-domain.com;
location /api/ {
proxy_pass http://127.0.0.1:3000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
- 保存后运行 sudo nginx -t && sudo systemctl reload nginx
- 注意:proxy_pass 末尾斜杠影响路径重写,要保持一致
基本上就这些。后续可按需配置 HTTPS(用 Certbot)、负载均衡、静态资源缓存等。不复杂但容易忽略 reload 和防火墙,动手前多 check 两遍。










