插件窝 干货文章 CentOS7下如何安装Nginx服务器

CentOS7下如何安装Nginx服务器

Nginx sudo systemctl 配置 455    来源:    2025-04-26

CentOS 7 下安装 Nginx 服务器指南

方法一:通过 EPEL 仓库安装(最简单)

  1. 添加 EPEL 仓库

    sudo yum install epel-release
    
  2. 安装 Nginx

    sudo yum install nginx
    
  3. 启动 Nginx 服务

    sudo systemctl start nginx
    
  4. 设置开机自启

    sudo systemctl enable nginx
    

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

  1. 创建 Nginx 官方仓库文件

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

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

    sudo yum install nginx
    
  4. 启动并启用服务

    sudo systemctl start nginx
    sudo systemctl enable nginx
    

基本配置与验证

  1. 检查 Nginx 状态

    sudo systemctl status nginx
    
  2. 测试 Nginx 是否运行: 在浏览器访问服务器的 IP 地址,应该能看到 Nginx 欢迎页面。

  3. 配置防火墙(如果启用了 firewalld):

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

常用管理命令

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

配置文件位置

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

安装完成后,您可以根据需要修改配置文件来设置虚拟主机、SSL 证书等高级配置。