vue3 history 模式配合 nginx 多 location 配置

1,043 阅读2分钟

vue router 有 Hash, HTML5 不同的历史模式

官方文档:

  1. hash 模式是用 createWebHashHistory() 创建的
import { createRouter, createWebHashHistory } from 'vue-router'

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

它在内部传递的实际 URL 之前使用了一个哈希字符(#)。由于这部分 URL 从未被发送到服务器,所以它不需要在服务器层面上进行任何特殊处理。不过,它在 SEO 中确实有不好的影响。如果你担心这个问题,可以使用 HTML5 模式。

  1. 用 createWebHistory() 创建 HTML5 模式,推荐使用这个模式:
import { createRouter, createWebHistory } from 'vue-router'

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

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

不过,问题来了。由于我们的应用是一个单页的客户端应用,如果没有适当的服务器配置,用户在浏览器中直接访问 example.com/user/id,就会得… 404 错误。这就丑了。

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

1. 根目录时

a. vue 项目配置

router.ts

import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
const router = createRouter({
  history: createWebHistory(),
  routes
});
b. nginx 配置
 location / {
   	 # root地址自定义
        root /data/pc;
        client_max_body_size    1000m;
        default_type application/json;
        index  index.html index.htm;
        # 解决前端页面history模式刷新404问题
        try_files $uri $uri/ /index.html;
 }

2. nginx 部署子目录时

a. vue 项目配置

这里需要注意, 如果你部署到子目录,你应该使用Vue CLI 的 publicPath 配置和相关的路由器的 base 属性。以使用子目录而不是根目录。

router.ts

import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

vue.config.js 文件配置

publicPath: process.env.NODE_ENV === "production" ? "/pc" : "/"
b. nginx 配置

location /pc {
    alias F:\\xxx\dist;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
}

history.png

如果要配置其他子目录时,在nginx上增加 location 配置即可如:

location /h5 {
    alias E:\\xxx\dist;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
}

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 2 天,点击查看活动详情