@TOC
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配置
服務(wù)端nginx的一開始配置如下(假設(shè)域名為:xx.xxx.com):
[***** ~]# cat /Data/app/nginx/conf/vhosts/xx.xxx.com.conf
server {
listen 80;
server_name testwx.wangshibo.com;
root /Data/app/xqsj_wx/dist;
index index.html;
access_log /var/log/testwx.log main;
}
修改如下:
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 中間件
Internet Information Services (IIS)
- 安裝 IIS UrlRewrite
- 在你的網(wǎng)站根目錄中創(chuàng)建一個(gè) web.config 文件,內(nèi)容如下:
<?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 主機(jī)
在你的 firebase.json 中加入:
{
"hosting": {
"public": "dist",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
最后
給個(gè)警告躯护,因?yàn)檫@么做以后喜爷,你的服務(wù)器就不再返回 404 錯(cuò)誤頁面,因?yàn)閷τ谒新窂蕉紩祷?index.html 文件匀哄。為了避免這種情況聊训,你應(yīng)該在 Vue 應(yīng)用里面覆蓋所有的路由情況,然后在給出一個(gè) 404 頁面恢氯。
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})