使用面板很方便,但是为了深度理解 Nginx 的原理,还是要学习一下 CentOS7 上如何安装 Nginx

##前提条件 请确保以具有 root 权限的用户身份登录, 并且没有在端口 80 或 443 上运行任何其他服务。

在 CentOS 上安装 Nginx

1.EPEL 存储库

Nginx 包在 EPEL 存储库中可用。如果还没有安装 EPEL 存储库

1
yum install epel-release

2.通过 yum 命令安装 Nginx

1
yum install nginx

如果这是第一次从 EPEL 存储库安装软件包,yum 可能会提示导入 EPEL GPG 密钥

1
2
3
4
5
6
7
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
Importing GPG key 0x352C64E5:
Userid     : "Fedora EPEL (7) <epel@fedoraproject.org>"
Fingerprint: 91e9 7d7c 4a5e 96f1 7f3e 888f 6a2f aea2 352c 64e5
Package    : epel-release-7-noarch (@extras)
From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
Is this ok [y/N]:

如果是这种情况,请键入 y 并点击 Enter。

3.启用并启动 Nginx 服务

1
2
systemctl enable nginx //开机启动
systemctl start nginx  //启动Nginx服务

使用以下命令检查 Nginx 服务的状态:

1
systemctl status nginx

4.防火墙开放端口

使用以下命令打开必要的端口:

1
2
3
firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-service=https
firewall-cmd --reload

5.验证 Nginx

浏览器输入 http://IP

使用 systemctl 管理 Nginx 服务

可以像管理任何其他 systemd 单元一样管理 Nginx 服务。

停止 Nginx 服务

1
systemctl stop nginx

启动 Nginx 服务

1
systemctl start nginx

重新启动 Nginx 服务

1
systemctl restart nginx

重新加载 Nginx 服务配置

1
systemctl reload nginx

Nginx 服务开机启动

1
systemctl enable nginx

禁用 Nginx 服务开机启动

1
systemctl disable nginx

Nginx 配置文件的结构和最佳实践

  • 所有 Nginx 配置文件都位于该/etc/nginx/目录中。
  • 主要的 Nginx 配置文件是
1
/etc/nginx/nginx.conf
  • 为了使 Nginx 配置更易于维护,建议为每个域创建一个单独的配置文件。
  • 新的 Nginx 服务器块文件必须.conf 以/etc/nginx/conf.d 目录结尾并存储在目录中。我们可以根据需要拥有任意数量的服务器块。例如,如果我们的域名是 xgdan.com 那么我们的配置文件应该命名为
1
/etc/nginx/conf.d/xgdan.com.conf
  • Nginx 日志文件(access.log 和 error.log)位于该/var/log/nginx/目录中。建议有不同 access,并 error 为每个服务器模块的日志文件。
  • 我们可以将域文档根目录设置为我们想要的任何位置。webroot 最常见的位置包括:
1
2
3
4
5
/home/<user_name>/<site_name>
/var/www/<site_name>
/var/www/html/<site_name>
/opt/<site_name>
/usr/share/nginx/html