插件窝 干货文章 Centos下如何安装Nginx

Centos下如何安装Nginx

Nginx 安装 sudo bash 82    来源:    2025-04-23

在CentOS系统上安装Nginx可以通过以下步骤完成,这里提供两种常用方法:YUM仓库安装和源码编译安装。


方法一:通过YUM仓库安装(推荐)

特点:简单快捷,自动处理依赖关系,适合生产环境。

1. 更新系统包

sudo yum update -y

2. 添加EPEL仓库(Extra Packages for Enterprise Linux)

Nginx在默认的CentOS仓库中可能不存在,需要先启用EPEL:

sudo yum install epel-release -y

3. 安装Nginx

sudo yum install nginx -y

4. 启动Nginx并设置开机自启

sudo systemctl start nginx
sudo systemctl enable nginx

5. 验证安装

  • 检查服务状态: bash sudo systemctl status nginx
  • 访问默认页面: 在浏览器中输入服务器IP地址(如 http://your_server_ip),看到Nginx欢迎页即表示成功。

6. 配置防火墙(如果启用)

允许HTTP(80)和HTTPS(443)流量:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

方法二:源码编译安装

特点:可自定义模块和版本,适合需要特定配置的场景。

1. 安装编译依赖

sudo yum groupinstall "Development Tools" -y
sudo yum install pcre-devel zlib-devel openssl-devel -y

2. 下载Nginx源码

访问Nginx官网获取最新稳定版链接,例如:

wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar -zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3

3. 编译并安装

./configure --prefix=/usr/local/nginx --with-http_ssl_module
make
sudo make install

4. 启动Nginx

/usr/local/nginx/sbin/nginx

5. 验证安装

curl http://localhost

或浏览器访问服务器IP。

6. 配置系统服务(可选)

创建Systemd服务文件 /etc/systemd/system/nginx.service

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target

然后启用服务:

sudo systemctl daemon-reload
sudo systemctl start nginx
sudo systemctl enable nginx

常见问题解决

  1. 端口冲突:如果Apache等服务占用了80端口,需先停止它们(sudo systemctl stop httpd)。
  2. SELinux阻止:临时禁用 setenforce 0 或调整策略。
  3. 权限问题:确保Nginx用户(通常为 nginxwww-data)对相关目录有访问权限。

总结

  • 推荐方法:生产环境优先使用YUM安装(方法一),简单且易于维护。
  • 高级需求:如需定制模块或版本,选择源码编译(方法二)。

安装完成后,配置文件路径: - YUM安装:/etc/nginx/nginx.conf - 源码安装:/usr/local/nginx/conf/nginx.conf