一、CentOS 7.9 可安装的 Nginx 最高版本
CentOS 7.9 官方 yum 源中的 Nginx 版本较低(约 1.12.x),但通过 Nginx 官方源可以安装到1.24.x 系列(这是 Nginx 稳定版中支持 CentOS 7 的最高版本,Nginx 1.25+ 及以上的主线版不再支持 CentOS 7)。
二、安装步骤(推荐官方源方式)
步骤 1:安装依赖
首先安装编译和运行 Nginx 所需的依赖包:
# 安装基础依赖
yum install -y gcc gcc-c++ make pcre pcre-devel zlib zlib-devel openssl openssl-devel wget
步骤 2:配置 Nginx 官方 yum 源
CentOS 7 默认没有 Nginx 官方源,需要手动添加:
# 创建 Nginx 源配置文件
vi /etc/yum.repos.d/nginx.repo
将以下内容粘贴到文件中(适配 CentOS 7 的官方源):
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
nginx-stable:稳定版(推荐,最高 1.24.x),enabled=1表示启用;nginx-mainline:主线版(不支持 CentOS 7),保持enabled=0即可。
步骤 3:安装 Nginx
# 清理 yum 缓存并安装 Nginx
yum clean all && yum makecache
yum install -y nginx
步骤 4:验证安装并启动
# 查看安装的 Nginx 版本(确认版本号)
nginx -v
# 启动 Nginx 并设置开机自启
systemctl start nginx
systemctl enable nginx
# 检查 Nginx 运行状态
systemctl status nginx
步骤 5:开放 80 端口(可选)
如果开启了防火墙,需要放行 80 端口(HTTP 默认端口):
# 临时放行 80 端口
firewall-cmd --add-port=80/tcp --permanent
# 重启防火墙生效
firewall-cmd --reload
步骤 6:验证访问
在浏览器中输入服务器 IP 地址,若看到 Nginx 的默认欢迎页面,说明安装成功。
三、补充说明(编译安装方式,可选)
如果需要自定义编译参数,也可以手动编译安装 1.24.x 版本,步骤如下:
# 下载 Nginx 1.24.0 源码包(CentOS 7 支持的最高稳定版)
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_stub_status_module
# 编译并安装
make && make install
# 创建系统服务(方便管理)
vi /usr/lib/systemd/system/nginx.service
粘贴以下内容:
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target
然后启动并设置自启:
systemctl daemon-reload
systemctl start nginx
systemctl enable nginx
总结
- CentOS 7.9 可安装的 Nginx 最高稳定版本为1.24.x(官方源),主线版 1.25+ 不再支持 CentOS 7;
- 推荐使用Nginx 官方 yum 源安装,步骤简单且便于后续升级;
- 核心步骤:安装依赖 → 配置官方源 → 安装 Nginx → 启动并验证。