第一次配置try_files是在Vue Router使用history模式时,如果没有适当的服务器配置,用户直接访问或刷新页面时,会出现404。
如下:

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    //...
  ],
})

当使用这种历史模式时,URL 会看起来很 "正常",例如 https://example.com/user/id。漂亮!

但是如果没有适当的服务器配置,用户在浏览器中直接访问 https://example.com/user/id,就会得到一个 404 错误。这就尴尬了。

要解决这个问题,你需要做的就是在你的服务器上添加一个简单的回退路由。如果 URL 不匹配任何静态资源,它应提供与你的应用程序中的 index.html 相同的页面。

如果是Nginx服务器,通常如下配置即可:

location / {
  try_files $uri $uri/ /index.html;
}

Vue单页面部署子目录刷新问题

正常情况下,如果Vue单页面部署在NGINX根目录,上述配置是没有问题的,但是如果是不是在子目录,上述配置就不生效了。

例如,vue单页面部署在 childwww 目录, 即通过https://itshizhan.com/childwww访问,如果有一个路由,例如 list, 当我们直接访问或刷新时,会直接跳转到 https://itshizhan.com/, 但是,我们期望的肯定是回到https://itshizhan.com/childwww

该如何配置呢?添加如下配置即可:

location /childwww {
  try_files $uri $uri/ /childwww;
}

文件重定向

http {

    include /etc/nginx/mime.types;

    server {

        listen 80;
        server_name nginx-handbook.test;

        root /srv/nginx-handbook-projects/static-demo;

        try_files /the-nginx-handbook.jpg /not_found;

        location /not_found {
                return 404 "sadly, you've hit a brick wall buddy!\n";
        }
    }
}

当项目根目录不存在/srv/nginx-handbook-projects/static-demo/the-nginx-handbook.jpg 文件时,重定向到 /not_found 路由。

结合$uri变量

$uri指当前的请求URI,不包括任何参数。

$request_uri是浏览器发起的不做任何修改的原生URI,包括参数,但不包括协议及主机名。

 server {

        listen 80;
        server_name nginx-handbook.test;

        root /srv/nginx-handbook-projects/static-demo;

        try_files $uri $uri/ /not_found;

        location /not_found {
                return 404 "sadly, you've hit a brick wall buddy!\n";
        }
    }

首先查找URI 文件,如果没有,则查询 URI目录,默认查询目录下的index.html文件, 如果都没有,则返回404

try_files 跳转到变量

server {
    listen 80;
    server itshizhan.com;
    root html;
    index index.html index.htm;
    
    location /golang {
        try_files /a.html /b.html @notfound;
    }
    
    location @notfound {
        rewrite ^/(.*)$ www.vocabpark.com;  # 跳转到www.vocabpark.com
    }
}

访问 /golang时,若没有 a.html 或b.html文件,则跳转到@notfound

当然跳转到变量后,也可以重新跳转到后端upstream.

例如:

upstream nbstudyapi {
    server 127.0.0.1:8080;
}

server {
    listen 80;
    server itshizhan.com;
    root html;
    index index.html index.htm;
    
    location /golang {
        try_files /a.html /b.html @notfound;
    }
    
    location @notfound {
        proxy_pass http://nbstudyapi;
    }
}