【问题标题】:How can I set up nginx to solve 404 not found on static file vue?如何设置 nginx 来解决静态文件 vue 上找不到 404?
【发布时间】:2020-06-06 16:34:00
【问题描述】:

我使用 nginx 来运行我的项目。所以我将 nginx 安装到我的本地主机来测试它

我在 localhost 上的配置 nginx 是这样的:

location / {
    root   html;
    index  index.html index.htm;
}

如果我刷新一个页面,它会出现这样的错误:

404 Not Found
nginx/1.14.0 (Ubuntu)

我在谷歌上搜索并得到一些参考。我尝试这样:

location / {
    root /www/dist;
    try_files $uri /index.html;
}

我工作。没有错误

然后我将我的项目部署到生产环境

我在生产中的配置 nginx 是这样的:

location / {
    root /www/dist;
    try_files $uri /index.html;
}

它也有效

但我的问题是我需要将位置更改为这样:

location /startup {
    root /www/dist;
    try_files $uri /index.html;
}

我在nginx中有很多项目。所以我必须添加/startup 以表明它是启动项目。但它会产生这样的错误:

404 Not Found
nginx/1.14.0 (Ubuntu)

我该如何解决这个问题?

【问题讨论】:

标签: vue.js nginx vue-component vuetify.js static-files


【解决方案1】:

当你在 nginx 中使用root 时,它总是追加到文件路径末尾的路由,但在使用/ 时这并不明显。因此,在您使用location / 的第一个示例中,它会在服务器上搜索此路径:

root + /www/dist + /

但是当你使用location /startup时,它会寻找这个不存在的路径:

root + /www/dist + /startup

所以要同时使用root 和“/startup”,您需要一个名为“startup”的目录。 但是,您可以使用别名。试试这个:

location /startup {
    alias /www/dist;
    try_files $uri $uri/ /startup/index.html;
}

Vue Router docs 也推荐类似的东西。 (但他们没有展示如何使用子文件夹alias。)

【讨论】:

  • 我尝试这样:location /startup/ { alias /www/dist; try_files $uri /index.html; }。但它不起作用。一样的
  • 我用try_files解决404 Not Found。如果我不使用它,它似乎不起作用
  • 我已经在我的本地主机上尝试过它并且它有效。但稍后我将在生产服务器上尝试。如果可行,我会接受你的回答
  • 我身上的任何好处都是上帝的作为,感谢您的鼓励。我使用alias链接了Vue路由器文档并稍微调整了答案以匹配文档建议的方式。
  • 是的,仍然是别名。现在唯一的区别是同时使用$uri $uri/ 而不仅仅是$uri
猜你喜欢
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-12
  • 2014-06-07
  • 2017-09-02
相关资源
最近更新 更多