Centos7下安装、配置Nginx

本文简要介绍下如何在Centos7下安装Nginx,以及Nginx配置简单说明。

  • 安装插件
  • 安装Nginx
  • 将Nginx配置为系统服务

 

一、安装插件

1.安装gcc

安装 nginx 需要先将官网下载的源码进行编译,编译依赖 gcc 环境,所以需要安装 gcc 环境。命令如下:

yum install gcc-c++

2.安装pcre、pcre-devel

pcre是一个perl库,包括perl兼容的正则表达式库,nginx的http模块使用pcre来解析正则表达式,所以需要安装pcre库。命令如下:

yum install -y pcre pcre-devel

3.安装zlib

zlib库提供了很多种压缩和解压缩方式,nginx使用zlib对http包的内容进行gzip。命令如下:

yum install -y zlib zlib-devel

4.安装openssl

OpenSSL 是一个强大的安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及 SSL 协议,并提供丰富的应用程序供测试或其它目的使用。nginx 不仅支持 http 协议,还支持 https,所以需要安装 OpenSSL 库。命令如下:

yum install -y openssl openssl-devel

 

二、安装Nginx

1.下载安装包,直接官网下载,地址:https://nginx.org/en/download.html


使用wget命令下载(推荐)。确保系统已经安装了wget,如果没有安装,执行 yum install wget 安装。下载Nginx命令如下:

wget -c https://nginx.org/download/nginx-1.18.0.tar.gz

2.下载成功后,解压,进入解压目录。命令如下:

tar -zxvf nginx-1.18.0.tar.gz
cd nginx-1.18.0

3.使用Nginx默认配置,命令如下:(当然也可以使用自定义配置,有兴趣的小伙伴可以自行研究下)

./configure --prefix=/usr/local/nginx --with-http_ssl_module

4.编译安装,命令如下:

make
make install

5.查找安装路径,命令如下:

whereis nginx

6.启动、停止、重启Nginx

cd /usr/local/nginx/sbin/

启动

./nginx

停止

./nginx -s quit  -- 此方式停止步骤是待nginx进程处理任务完毕进行停止。
./nginx -s stop  -- 此方式相当于先查出nginx进程id再使用kill命令强制杀掉进程。

重启

先停止再启动(推荐),即先执行停止命令再执行启动命令。命令如下:

./nginx -s quit
./nginx

重新加载配置文件

当 nginx的配置文件 nginx.conf 修改后,要想让配置生效,使用-s reload 命令则不用先停止 nginx再启动 nginx 即可将配置信息在 nginx 中生效。命令如下:

./nginx -s reload

查看nginx进程。命令如下:

ps aux|grep nginx

启动成功后,可以在浏览器中看到以下页面,至此,Nginx安装就完成了!

 

三、将Nginx配置为系统服务

切换到/lib/systemd/system/目录,创建nginx.service文件。命令如下:

cd /lib/systemd/system/
vim nginx.service

文件内容如下:

[Unit]
Description=nginx
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
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 quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target

保存文件并退出,执行以下命令使nginx开机启动

systemctl enable nginx.service

 

配置文件的解释:
[Unit]:服务的说明
Description:服务描述
After:服务类别
[Service]服务运行参数的设置
Type=forking后台运行
ExecStart启动命令
ExecReload重启命令
ExecStop停止命令
PrivateTmp=True表示给服务分配独立的临时空间
注意:[Service]的启动、重启、停止命令全部要求使用绝对路径
[Install]运行级别下服务安装的相关设置,可设置为多用户,即系统运行级别为3

 

最后,顺便做个备注:

启动Nginx服务:

systemctl start nginx.service

停止Nginx服务:

systemctl stop nginx.service

重启Nginx服务

systemctl restart nginx.service

 服务自动启动

systemctl enable nginx.service

服务禁止自动启动

systemctl disable nginx.service

查看服务状态

systemctl status nginx.service

显示所有已启动的服务

systemctl list-units --type=service

 

posted @ 2020-10-10 10:34  JcongJason  阅读(296)  评论(0编辑  收藏  举报