Nginx

Nginx是什么?

看一下官方介绍:

nginx (“engine x”) is an HTTP web server, reverse proxy, content cache, load balancer, TCP/UDP proxy server, and mail proxy server.

nginx(“ 引擎 X”)是一个 HTTP Web 服务器、反向代理、内容缓存、负载均衡器、TCP/UDP 代理服务器和邮件代理服务器。

安装Nginx

下载地址:https://nginx.org/en/download.html

选择某个版本后,可以复制链接地址,然后在服务器中通过wget命令远程下载,或先下载到本地,再上传到服务器。

我这里使用wget命令下载:

1
wget https://nginx.org/download/nginx-1.28.0.tar.gz

然后对下载的压缩包进行解压:

1
tar -zxf nginx-1.28.0.tar.gz

然后进入nginx-1.28.0目录,执行./configure命令:

1
2
cd nginx-1.28.0/
./configure

./configure命令执行完毕后,会生成一个Makefile文件,然后执行以下命令进行编译和安装,这一步会牵涉到创建文件夹操作,需要管理员权限。

1
2
3
su
# 输入密码进入root账号
make && make install

然后就可以使用nginx了:

1
2
cd /usr/local/nginx/sbin
./nginx

但我们不能每次都进入/usr/local/nginx/sbin执行启动命令,我们可以在/usr/local/bin/目录下创建一个名为nginx的软链接文件,指向真实的Nginx程序/usr/local/nginx/sbin/nginx

/usr/local/bin/ 是 Linux 系统默认的可执行文件搜索路径(包含在 $PATH 环境变量中)。创建链接后,只需在终端输入 nginx,系统会自动在 PATH 包含的目录中搜索并执行该命令,无需输入完整路径。

1
2
# ln -s nginx可执行命令路径 /usr/local/bin
ln -s /usr/local/nginx/sbin/nginx /usr/local/bin/

Nginx常用命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 测试配置文件:nginx 检查配置是否语法正确,然后尝试打开配置中引用的文件。
nginx -t

# 打印 nginx 版本
nginx -v # nginx version: nginx/1.28.0

# 打印 nginx 版本、编译器版本和配置参数
nginx -V

# 快速关闭 nginx 服务
nginx -s stop

# 正常关闭 nginx 服务
nginx -s quit

# 重新加载 nginx 配置文件
nginx -s reload

经过上述配置以后,我们还想将Nginx服务设置为开机自启:

1
systemctl enable nginx

但当我们进行回车操作后却显示:

Unit nginx.service could not be found.

这是因为Nginx服务在/usr/lib/systemd/system/nginx.service文件中没有配置,我们可以手动添加:

1
vi /etc/systemd/system/nginx.service

进入编辑器页面后,添加以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
[Unit]
Description=Nginx HTTP Server
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target

然后重新加载systemd配置文件:

1
systemctl daemon-reload

进行上述操作以后,我们就可以使用systemctl命令来启动、停止、重启Nginx服务了:

1
2
3
4
5
6
7
8
9
10
11
12
# 启动 Nginx
systemctl start nginx
# 停止 Nginx
systemctl stop nginx
# 重启 Nginx
systemctl restart nginx
# 查看 Nginx 状态
systemctl status nginx
# 配置 Nginx 为开机启动
systemctl enable nginx
# 禁止 Nginx 开机启动
systemctl disable nginx

还有一些与 Nginx 相关的命令,如下:

强制停止 Nginx(应急)

1
2
pkill nginx              # 通过进程名终止
killall nginx # 终止所有同名进程

有关 Nginx 的权限问题

当我们打算将项目交予 Nginx 代理是,可能会放到usr/local/nginx/html目录下,这时,但当我们操作时,往往因为权限问题是不能操作文件的,我们可以通过以下命令改变它的权限:

1
2
3
4
5
6
7
8
# 查看当前用户
whoami

# 更改所有权 直接一劳永逸,改变整个nginx下的权限
sudo chown -R $USER:$USER /usr/local/nginx

# 设置正确权限
sudo chmod -R 755 /usr/local/nginx

Nginx 配置 history 路由模式的项目

webpack搭建本地服务器中,我提到过,单页面应用采用history路由模式时,URL中文件路径在服务器上并不存在,当我们刷新时,会直接根据文件路径访问服务器的文件系统,结果当时是404找不到,为了解决这个问题,我们希望所有404请求都会被重定向到有效的页面。

在 Nginx 中可以通过try_files $uri $uri/ 有效html文件路径;达到上述预期效果:

1
2
3
4
5
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}