1、下载Nginx
在Nginx官网http://nginx.org/en/download.html选择需要的Nginx版本,
然后复制地址进行下载
wget http://nginx.org/download/nginx-1.16.1.tar.gz
2、安装编译环境
安装C/C++环境
yum install gcc
yum install gcc-c++ libstdc++-devel
3、编译源码
–prefix 参数指定安装目录,可以通过./configure --help 查看更多nginx编译时的参数
[root@localhost nginx-1.16.1]# ./configure --prefix=/usr/soft/nginx/ --with-http_ssl_module --with-stream
参数:–with-http_ssl_module 安装ssl
参数:—with-stream 安装stream模块
- 如果安装过程出现如下错误:
nginx error: the HTTP rewrite module requires the PCRE library.
安装pcre-devel解决
yum -y install pcre-devel
- 上面的错误解决之后,如果出现如下错误
./configure: error: the HTTP cache module requires md5 functions
from OpenSSL library. You can either disable the module by using
--without-http-cache option, or install the OpenSSL library into the system,
or build the OpenSSL library statically from the source with nginx by using
--with-http_ssl_module --with-openssl=<path> options.
解决:
yum -y install openssl openssl-devel
编译成功后输出Nginx运行目录、配置等信息
3、编译安装
[root@localhost nginx-1.16.1]# make && make install
成功后会生成nginx二进制文件,在源码目录的objs目录下
4、常用命令
进入到nginx的安装目录的sbin文件夹
- 启动/重新加载
./nginx -s reload
启动的时候可能会报这个错误:
nginx: [error] invalid PID number "" in "/run/nginx.pid"
遇到上面的错需要先执行:
./nginx -c /usr/soft/nginx/conf/nginx.conf
参数-c
表示使用指定的配置文件
- 停止
./nginx -s quit #优雅的停止
./nginx -s stop #立即停止
- 查看Nginx版本
./nginx -v # Nginx 安装的版本
./nginx -V #Nginx 编译时各种参数信息
5、设置开机启动
- 在系统服务目录里创建nginx.service文件
vim /lib/systemd/system/nginx.service
- 内容如下
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
ExecStart=/usr/soft/nginx/sbin/nginx
ExecReload=/usr/soft/nginx/sbin/nginx -s reload
ExecStop=/usr/soft/nginx/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
Description:描述服务
After:描述服务类别
[Service]服务运行参数的设置
Type=forking是后台运行的形式
ExecStart为服务的具体运行命令
ExecReload为重启命令
ExecStop为停止命令
PrivateTmp=True表示给服务分配独立的临时空间
注意:[Service]的启动、重启、停止命令全部要求使用绝对路径
[Install]运行级别下服务安装的相关设置,可设置为多用户,即系统运行级别为3
- 设置开机启动
systemctl enable nginx.service
- 其它命令
启动nginx服务
systemctl start nginx.service
设置开机自启动
systemctl enable nginx.service
停止开机自启动
systemctl disable nginx.service
查看服务当前状态
systemctl status nginx.service
重新启动服务
systemctl restart nginx.service
查看所有已启动的服务
systemctl list-units --type=service