安装步骤
以下安装命令均以root身份执行。
下载nginx源码
- 使用wget命令下载nginx源码(这里下载的是1.20.2版本)
wget http://nginx.org/download/nginx-1.20.2.tar.gz
- 解压源码压缩包到/usr/local/目录下
tar -xvf nginx-1.20.2.tar.gz -C /usr/local/
安装依赖
- nginx依赖PCRE(Perl Compatible Regular Expressions)库,所以需要先安装PCRE库
apt install libpcre3 libpcre3-dev
- 检查pcre是否安装成功
root@VM-0-15-ubuntu:~$ pcre-config --version
8.44
如果打印版本号,则说明pcre依赖已安装成功。
编译安装nginx
- 进入nginx的源码目录
cd /usr/local/nginx-1.20.2/
- 配置编译和安装选项
./configure
- 编译和安装
make && make install
如果在“2. 配置编译和安装选项”没有特别制定nginx的安装目录,默认将nginx安装在 /usr/local/nginx 目录下:
root@VM-0-15-ubuntu:/usr/local/nginx-1.20.2# ls /usr/local/nginx
client_body_temp conf fastcgi_temp html logs proxy_temp sbin scgi_temp uwsgi_temp
启动nginx
nginx的可执行文件在安装目录的sbin文件夹下:
root@VM-0-15-ubuntu:~# ls -lh /usr/local/nginx/sbin/
total 4.6M
-rwxr-xr-x 1 root root 4.6M Apr 4 23:08 nginx
可将其加入到环境变量中,这样,就可以直接直接使用nginx命令来启停和控制nginx服务器了:
- 在/etc/profile.d/目录下新建export_path.sh
root@VM-0-15-ubuntu:~# cd /etc/profile.d/
root@VM-0-15-ubuntu:/etc/profile.d# vim export_path.sh
export_path.sh的内容如下所示:
#!/bin/bash
export PATH=$PATH:/usr/local/nginx/sbin/
- 保存export_path.sh并添加可执行权限
root@VM-0-15-ubuntu:/etc/profile.d# chmod +x export_path.sh
- 使环境变量生效(实际上执行了/etc/profile.d/export_path.sh)
root@VM-0-15-ubuntu:/etc/profile.d# source /etc/profile
- 检查nginx的环境变量是否生效:
root@VM-0-15-ubuntu:/etc/profile.d# nginx -v
nginx version: nginx/1.20.2
打印出了nginx的版本,说明nginx的环境变量添加成功了。
使用以上方法添加环境变量,除手动执行source /etc/profile命令外,用户登录也能使环境变量生效。
注意:如果以普通用户登录系统,root用户的环境变量并未生效。因为,不同用户之间不共享PATH。执行sudo -s和su root切换至root身份并非 以root身份登录系统,因此,nginx的环境变量可能并未生效,则会出现nginx不存在的错误:
ubuntu@VM-0-15-ubuntu:~$ sudo -s
root@VM-0-15-ubuntu:~# nginx
Command 'nginx' not found, but can be installed with:
apt install nginx-core
apt install nginx-extras
apt install nginx-full
apt install nginx-light
root@VM-0-15-ubuntu:~# exit
exit
ubuntu@VM-0-15-ubuntu:~$ su root
Password:
root@VM-0-15-ubuntu:/home/ubuntu# nginx
Command 'nginx' not found, but can be installed with:
apt install nginx-core
apt install nginx-extras
apt install nginx-full
apt install nginx-light
以root身份登录系统的正确命令是:su - root
ubuntu@VM-0-15-ubuntu:~$ su - root
Password:
root@VM-0-15-ubuntu:~# nginx -v
nginx version: nginx/1.20.2
- 启动nginx
root@VM-0-15-ubuntu:~# start nginx
root@VM-0-15-ubuntu:~#
root@VM-0-15-ubuntu:~# ps -ef | grep nginx
root 3531 1 0 17:51 ? 00:00:00 nginx: master process nginx
nobody 3532 3531 0 17:51 ? 00:00:00 nginx: worker process
root 3579 3499 0 17:52 pts/1 00:00:00 grep --color=auto nginx
6. nginx启停控制
start nginx //启动nginx的命令。
nginx -s quit //此方式停止步骤是待nginx进程处理任务完毕进行停止。
nginx -s stop //此方式相当于先查出nginx进程id再使用kill命令强制杀掉进程。
nginx -s reload //重新加载配置文件:当 nginx的配置文件 nginx.conf 修改后,要想让配置生效需要重启 nginx,使用-s reload不用先停止 nginx再启动 nginx 即可将配置信息在 nginx 中生效