vue框架下部署上線後刷新報404問題解決方案

@TOCjavascript

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>
複製代碼

nginx配置

location / {
  try_files $uri $uri/ /index.html;
}
複製代碼

vue history模式下nginx配置

服務端nginx的一開始配置以下(假設域名爲:xx.xxx.com): [***** ~]# cat /Data/app/nginx/conf/vhosts/xx.xxx.com.confphp

server {
         listen 80;

         server_name testwx.wangshibo.com;
         root /Data/app/xqsj_wx/dist;
         index index.html;

         access_log /var/log/testwx.log main;

}
複製代碼

修改以下:html

server {
         listen 80;

         server_name testwx.wangshibo.com;
         root /Data/app/xqsj_wx/dist;
         index index.html;
         access_log /var/log/testwx.log main;
         
		## 注意從這裏開始
         location / {
             try_files $uri $uri/ @router;
             index index.html;
         }

        location @router {
            rewrite ^.*$ /index.html last;
        }

}
複製代碼

原生 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 的 Express

對於 Node.js/Express,請考慮使用 connect-history-api-fallback 中間件vue

Internet Information Services (IIS)

  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

rewrite {
    regexp .*
    to {path} /
}
複製代碼

Firebase 主機

在你的 firebase.json 中加入:java

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

最後

給個警告,由於這麼作之後,你的服務器就再也不返回 404 錯誤頁面,由於對於全部路徑都會返回 index.html 文件。爲了不這種狀況,你應該在 Vue 應用裏面覆蓋全部的路由狀況,而後在給出一個 404 頁面。nginx

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '*', component: NotFoundComponent }
  ]
})
複製代碼
相關文章
相關標籤/搜索