nginx 代理二级目录访问 nuxtjs 项目 404 错误

本文 nuxt 版本 2.14.6!

能遇到此错误实属不易,先说说问题怎么产生的:

项目需求:nuxtjs 服务端渲染项目,由于某些不可抗拒原因,
部署到生产环境时候只能使用二级目录访问,比如: http://xxx.com/node/
由于是 nuxtjs 新手,部署到生产环境时,项目运行在 localhost:3000,然后使用了 nginx 代理,配置如下:

nginx.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
server {
listen 80;
server_name localhost;
# nuxt
location /node/ {
proxy_pass http://127.0.0.1:3000/;
}
# 服务端资源代理
location /_nuxt {
proxy_pass http://127.0.0.1:3000;
}
# static 中的 js 代理
location /js {
proxy_pass http://127.0.0.1:3000;
}
}

此处省略其他配置,仅有代理相关的配置在此处。

此配置之后请求 http://localhost/node/ 将会打开 http://127.0.0.1:3000/ 的页面。

配置很不错,项目请求也是 200,但是页面始终会返回404错误(页面内容一闪而过,然后会出现404的错误页面),启动开发环境测试,会发现报错:

1
[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.

折腾一番,并没发现任何问题,服务端接口请求也正常,控制台除了上面报错,也没打印其他任何错误。

处理办法

各种办法折腾过之后,发现 nuxt 本身可支持二级目录运行,结合 404 页面问题是正常内容一闪而过再出现的,
初步怀疑可能是后端路由与前端路由不匹配(后端访问的根路径 / ,前端访问的是 /node/),造成前端 js 的路由报错,返回了 404 页面。

  • 修改 nuxt.config.js 让其在二级目录运行
nuxt.config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 开发环境还是在根目录运行,生产环境在二级目录 /node 运行
const routerPrefix = process.env.NODE_ENV === 'production' ? '/node' : '';
const config = {
router: {
base: routerPrefix,
},
head: {
link: [
// static 目录中的 js 文件也需要加上前缀
{ rel: 'stylesheet', href: routerPrefix + '/js/swiper-min.css' },
],
script: [
// static 目录中的 js 文件也需要加上前缀
{ src: routerPrefix + '/js/swiper-min.js', async: false, defer: true },
],
},
// 省略其他配置
};
export default config;
  • 重新编译打包,重新部署生产环境,重启 nuxt
1
2
3
$ npm run build
...
$ npm run start
  • 修改 nginx 配置,重启 nginx
nginx.conf
1
2
3
4
5
6
7
8
server {
listen 80;
server_name localhost;
# nuxt
location /node/ {
proxy_pass http://127.0.0.1:3000;
}
}

注意: nginx.conf 配置中的 http://127.0.0.1:3000 后面没有斜线 / ,对比上面配置是有斜线的,
没有斜线表示请求 http://localhost/node/ 将会打开 http://127.0.0.1:3000/node/ 的页面,
有斜线会打开 http://127.0.0.1:3000/

再次请求 http://localhost/node/ ,页面不在报错 404,所有内容正常。

总结

以上问题大概率是:后端路由与前端路由不匹配造成,当然要找到具体原因得去扒源码才行了。

nuxt 运行在二级目录有一个好处是 nginx 只需要配置一个代理就行,不需要多次配置项目资源的请求代理。

本文由 linx(544819896@qq.com) 创作,采用 CC BY 4.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。本文链接为: https://blog.jijian.link/2020-12-09/nginx-proxy-nuxtjs-404/

如果您觉得文章不错,可以点击文章中的广告支持一下!