插件窝 干货文章 CentOS7如何安装Nginx并配置自动启动

CentOS7如何安装Nginx并配置自动启动

Nginx sudo 配置 systemctl 768    来源:    2025-04-25

CentOS 7 安装 Nginx 并配置自动启动指南

安装Nginx

方法一:从EPEL仓库安装(推荐)

  1. 首先安装EPEL仓库:

    sudo yum install epel-release
    
  2. 更新yum缓存:

    sudo yum update
    
  3. 安装Nginx:

    sudo yum install nginx
    

方法二:从Nginx官方仓库安装(获取最新版本)

  1. 创建Nginx官方仓库文件:

    sudo vi /etc/yum.repos.d/nginx.repo
    
  2. 添加以下内容:

    [nginx]
    name=nginx repo
    baseurl=http://nginx.org/packages/centos/7/$basearch/
    gpgcheck=0
    enabled=1
    
  3. 安装Nginx:

    sudo yum install nginx
    

配置Nginx自动启动

  1. 启动Nginx服务:

    sudo systemctl start nginx
    
  2. 设置开机自动启动:

    sudo systemctl enable nginx
    
  3. 检查Nginx状态:

    sudo systemctl status nginx
    

防火墙配置(如果需要外部访问)

  1. 允许HTTP(80)和HTTPS(443)端口:

    sudo firewall-cmd --permanent --zone=public --add-service=http
    sudo firewall-cmd --permanent --zone=public --add-service=https
    
  2. 重新加载防火墙:

    sudo firewall-cmd --reload
    

验证安装

  1. 在浏览器中访问服务器的IP地址,应该能看到Nginx欢迎页面

  2. 或者使用curl命令:

    curl http://localhost
    

常用管理命令

  • 启动Nginx:sudo systemctl start nginx
  • 停止Nginx:sudo systemctl stop nginx
  • 重启Nginx:sudo systemctl restart nginx
  • 重新加载配置(不中断服务):sudo systemctl reload nginx
  • 检查配置语法:sudo nginx -t
  • 查看Nginx版本:nginx -v

配置文件位置

  • 主配置文件:/etc/nginx/nginx.conf
  • 默认服务器配置:/etc/nginx/conf.d/default.conf
  • 网站根目录:/usr/share/nginx/html
  • 日志文件:/var/log/nginx/