静态文件vue 404 not found 怎么设置nginx解决?

How can I set up nginx to solve 404 not found on static file vue?

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

我在本地主机上的 nginx 配置是这样的:

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

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

404 Not Found
nginx/1.14.0 (Ubuntu)

我在 google 上搜索,得到了一些参考。我这样尝试:

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)

我该如何解决这个问题?

当你在 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。)