Has anyone managed to figure out how to make Vue.js work with history mode
with GitHub or GitLab Pages?
It works with hash mode
, but I don’t want to use hash mode
for SEO related reasons.
Reference for router modes: https://router.vuejs.org/en/essentials/history-mode.html
8
Answers
You could use a
404.html
hack https://github.com/rafrex/spa-github-pages/blob/gh-pages/404.htmlOr you can try to pre rendering your vue into static html
https://nuxtjs.org/guide#static-generated-pre-rendering-
I found a solution that works for me in this article.
To summarize the solution, I created the following
404.html
file and added it to the project’s root folder.I then added this javascript in the
index.html
:Run into same issue, found this question & tried both solution above but no luck. Then tried combine them like this:
Here my
404.html
fileAnd here’s my
main.js
fileAnd it works
A little late to the party but I have a method to do this. I am using Vue CLI 3 and GitHub pages.
First of all, I commit all the source file into a source branch, and commit the
dist
folder (generated by Vue) to the master branch using the following shell command:When GitHub pages can’t find the route, it uses
404.html
. The deploy program I wrote makes a copy of index.html and names it 404.html. That’s why it works.Edit
Just realised that this wouldn’t be good for SEO purposes as it returns a 404 response and Google won’t index it.
Based on Fery’s solution, I think instead of handling redirect when creating Vue instance, the Navigation Guards could work better.
I basically added a beforeEnter guard for the index route, so that the index page will be skipped and directly go to the target page.
Hope this is helpful.
Not sure about GitLab Pages, but in GitHub Pages you can serve your whole Vue.js Application through the 404.html file instead of the index.html file. Simply rename the index.html file to 404.html file on deploy.
EDIT:
As pointed out in the comments, this has the side effect of having GitHub/GitLab serve your website with a 404 status code.
GitLab Answer
For those using GitLab there is now support to redirect to index.html using a
_redirects
file in your public folder.Steps:
_redirects
in the public folderDocumentation: https://docs.gitlab.com/ee/user/project/pages/redirects.html#rewrite-all-requests-to-a-root-indexhtml
2021 Solution for vue3 & vue-cli:
Follow this with "Basic instructions":
https://github.com/rafgraph/spa-github-pages#usage-instructions
no need to change
var pathSegmentsToKeep = 0;
the 404.html.and then in the
vue.config.js
:then the spa is good to go~