Vue应用部署到服务器由于路由的history模式下刷新当前路由出现404的问题

用于默认模式vue-router散模式 -它使用URL的哈希来模拟一个完整的URL,这样的页面不会被重新加载的URL发生变化时。

为了摆脱哈希,我们可以使用路由器的历史模式,它利用history.pushStateAPI实现URL导航而无需重新加载页面:

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

 

使用历史记录模式时,URL将显示为“正常”,例如http://oursite.com/user/id

但是出现了一个问题:由于我们的应用程序是单页客户端应用程序,如果没有正确的服务器配置,如果用户http://oursite.com/user/id直接在浏览器中访问,则会收到404错误。现在那很难看。

不用担心:要解决此问题,您需要做的就是向服务器添加一个简单的全部回退路由。如果网址与任何静态资源都不匹配,则该网址应与index.html您的应用所在的网页相同。

示例服务器配置

Apache


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

而不是mod_rewrite,你也可以使用。FallbackResource

#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.htm', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.htm" 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)
})

#表达Node.js

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

Internet信息服务(IIS)

  1. 安装IIS UrlRewrite
  2. web.config使用以下内容在站点的根目录中创建文件:


  
    
      
        
          
          
            
            
          
          
        
      
    
  

Caddy

rewrite {
    regexp .*
    to {path} /
}

Firebase hosting

将此添加到您的firebase.json

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

注意

有一点需要注意:您的服务器将不再报告404错误,因为所有未找到的路径现在都会提供您的index.html文件。要解决此问题,您应该在Vue应用程序中实现一个全能路径以显示404页面:

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '*', component: NotFoundComponent }
  ]
})

或者,如果您使用的是Node.js服务器,则可以通过使用服务器端的路由器来匹配传入的URL来实现回退,如果没有匹配的路由,则使用404进行响应。有关更多信息,请查看Vue服务器端呈现文档。

 

参考文档:https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations

你可能感兴趣的:(vue)