Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
在解決問題之道上不斷前行
參考資料:
跟上次部署在 AWS 的問題很類似=>AWS Cloudfront 部署靜態網站出現 X-cache: Error from cloudfront 訊息,當 vue 的 SPA 部署在 github page ,並且設定自訂網域,如果是用 vue-route ,例如
找了幾種做法,這個解決法最簡易直覺,分享一下。
這做法就是在部署後產生的 index.html 直接重新導向自己,包含 404.html。
我的理解是,當訪問
記得加上檔案 public/404.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CHANGE THIS TO YOUR TITLE</title>
<script type="text/javascript">
var pathSegmentsToKeep = 0;
var l = window.location;
l.replace(
l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +
l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +
(l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
l.hash
);
</script>
</head>
<body>
</body>
</html>
index.html 則需要再加上自我轉址
<script type="text/javascript">
// MIT License
// https://github.com/rafgraph/spa-github-pages
// This script checks to see if a redirect is present in the query string,
// converts it back into the correct url and adds it to the
// browser's history using window.history.replaceState(...),
// which won't cause the browser to attempt to load the new url.
// When the single page app is loaded further down in this file,
// the correct url will be waiting in the browser's history for
// the single page app to route accordingly.
(function(l) {
if (l.search[1] === '/' ) {
var decoded = l.search.slice(1).split('&').map(function(s) {
return s.replace(/~and~/g, '&')
}).join('?');
window.history.replaceState(null, null,
l.pathname.slice(0, -1) + decoded + l.hash
);
}
}(window.location))
</script>
強制讓瀏覽器寫入原位置
基本上就可以運作了,但由於這是取巧的做法,可能會影響 SEO ,使用時要考慮一下喔。