一直以来项目都是路由到特定端口的根目录,简单配置一下就好。今天要部署一套前端到指定的子目录,复制了一份之前的根目录 server 配置,简单的将 location 的路由地址由 /替换为指定子目录后,其他配置不变。部署上去测试发现直接 404 Not Found。😐

问题分析

大概的 Nginx 配置如下:

server {
    listen 8000;
    server_name www.test.cn;

    location /20002 {
        root /www/test/20002/dist;

        index index.html;
    }
}

这个配置是直接从其他根目录的 server 复制过来的。打开 server_name:8000/20002 会直接报 404 Not Found。

首先去绑定的目录 /www/test/20002/dist 下查看是否由对应 Index.html 文件,有的,不是网页文件的问题。那应该就是我配置文件写的不对。将 location 改为 /,重启 Nginx,直接访问 server_name:8000 可以成功显示页面。问题应该是处在子目录的路由配置上。配置里就两个参数。。

  • root 用来指定路由到哪里。
  • index 用来设置默认访问的文件。

看起来都没啥问题,尝试进行搜索。

寻找原因

搜索 Nginx 路由子目录的方法,查询到 Nginx 路由静态网页由两种方法,一个是 root,一个是 alias。两种方法对请求文件的寻找路径不同。

  • root

    • 当使用 root 指令并且没有使用精确匹配(使用 =)时,root 方法会将请求的路径拼接到 root 所设置的路径后。最终路径为:root + location
  • alias

    • 当使用 alias 指令时,alias 方法会将访问的文件路径用 alias 替换。最终路径为:alias

举个例子

location /20002 {
    root /www/test/20002/dist;
    # ...
}

使用 root 方法来路由时,当我们访问 /20002/css/style.css 时,Nginx 会寻找 /www/test/20002/dist/20002/css/style.css 文件。

location /20002 {
    alias /www/test/20002/dist;
    # ...
}

使用 alias 来路由时,当我们访问 /20002/css/style.css 时,Nginx 会寻找 /www/test/20002/dist/css/style.css 文件。

所以,当我直接复制根目录的配置,简单修改一下 location 来进行子页面的路由时会出现 404 Not Found 的错误。当我访问 server_name:8000/20002/index.html 时,实际上 Nginx 在寻找 /www/test/20002/dist/20002/index.html 。是找不到这个文件的。

解决方法

找到了报错原因那解决就很简单了,根据上面的说明将 root 方法更改为 alias 即可。最终代码为:

server {
    listen 8000;
    server_name www.test.cn;

    location /20002 {
        alias /www/test/20002/dist;

        index index.html;
    }
}

这样访问 server_name:8000/20002/index.html 会被 Nginx 路由到 /www/test/20002/dist/index.html 这样路径就是正确的了。

参考