• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • 不同的历史记录模式

    在创建路由器实例时,history配置允许我们在不同的历史模式中进行选择。

    Hash 模式

    hash 模式是用createWebHashHistory()创建的:

    import { createRouter, createWebHashHistory } from 'vue-router'
    
    const router = createRouter({
      history: createWebHashHistory(),
      routes: [
        //...
      ],
    })
    

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


    HTML5 模式

    createWebHistory()创建 HTML5 模式,推荐使用这个模式:

    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相同的页面。漂亮依旧!


    服务器配置示例

    注意:下列示例假设你在根目录服务这个应用。如果想部署到一个子目录,你需要使用 Vue CLI 的publicPath选项和相关的 router base property。你还需要把下列示例中的根目录调整成为子目录(例如,将RewriteBase/替换为RewriteBase/name-of-your-subfolder/)。

    nginx

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


    原生 Node.js

    const http = require('http')
    const fs = require('fs')
    const httpPort = 80
    
    http
      .createServer((req, res) => {
        fs.readFile('index.html', 'utf-8', (err, content) => {
          if (err) {
            console.log('We cannot open "index" file.')
          }
    
          res.writeHead(200, {
            'Content-Type': 'text/html; charset=utf-8',
          })
    
          res.end(content)
        })
      })
      .listen(httpPort, () => {
        console.log('Server listening on: http://localhost:%s', httpPort)
      })
    


    Express + Node.js

    对于 Node.js/Express,请考虑使用connect-history-api-fallback中间件。


    Apache

    <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index\.html$ - [L]
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /index.html [L]
    </IfModule>
    

    也可以使用FallbackResource代替mod_rewrite


    IIS(Internet Information Services)

    1. 安装 IIS UrlRewrite
    2. 在你的网站根目录中创建一个web.config文件,内容如下:
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <system.webServer>
        <rewrite>
          <rules>
            <rule name="Handle History Mode and custom 404/500" stopProcessing="true">
              <match url="(.*)" />
              <conditions logicalGrouping="MatchAll">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
              </conditions>
              <action type="Rewrite" url="/" />
            </rule>
          </rules>
        </rewrite>
      </system.webServer>
    </configuration>
    


    Caddy v2

    try_files {path} /
    


    Caddy v1

    rewrite {
        regexp .*
        to {path} /
    }
    


    Firebase hosting

    在你的firebase.json中加入:

    {
      "hosting": {
        "public": "dist",
        "rewrites": [
          {
            "source": "**",
            "destination": "/index"
          }
        ]
      }
    }
    


    Netlify

    创建一个 _redirects 文件,包含在你的部署文件中:

    /* /index.html 200
    

    在 vue-cli、nuxt 和 vite 项目中,这个文件通常放在名为 static 或 public 的目录下。

    你可以在 Netlify 文档中找到更多关于语法的信息。你也可以创建一个 netlify.toml 来结合其他 Netlify 功能的重定向。


    警告

    给个警告,因为这么做以后,你的服务器就不再返回 404 错误页面,因为对于所有路径都会返回index.html文件。为了避免这种情况,你应该在 Vue 应用里面覆盖所有的路由情况,然后再给出一个 404 页面。

    const router = createRouter({
      history: createWebHistory(),
      routes: [{ path: '/:pathMatch(.*)', component: NotFoundComponent }],
    })
    

    或者,如果你使用 Node.js 服务器,你可以用服务端路由匹配到来的 URL,并在没有匹配到路由的时候返回 404,以实现回退。

    上篇:路由组件传参

    下篇:导航守卫