Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a configuration in Github Pages that allows you to redirect everything to index.html for a Single Page App?

I'm trying to post my SPA app that works fine locally but when I push it to Github Pages, the interior pages don't register if you navigate to them directly.

For example http://USER.github.io/PROJECT_NAME/ works but http://USER.github.io/PROJECT_NAME/about doesn't because theres no redirect or rewrite. The index.html is located at the root of the project.

like image 210
tkiethanom Avatar asked Mar 29 '16 22:03

tkiethanom


People also ask

How do I redirect a GitHub page?

The redirect is accomplished with a <meta> tag. By setting the http-equiv attribute to refresh and the content attribute to 0; URL=https://example.com/ we will redirect the user to 'https://example.com/'.

Can GitHub Pages be dynamic?

GitHub Pages doesn't support dynamic websites or anything requiring a backend or secret data. There are other sites that provide this kind of hosting, such as Netlify and Heroku, along with many others.

Can you use HTML in GitHub Pages?

GitHub Pages lets you take a GitHub repository and turn it into a webpage. In other words, you can use a GitHub repository to host your HTML, CSS, and JavaScript files.


1 Answers

If you are creating react app and you want to use Browser router in your gh pages the solution is to create 404.html file in your root directory and copy all the content in index.html to 404.html after you have build your react-app.

When a user try accessing your page e.g https://successtar.github.io/teamwork/ GitHub will serve your index.html page while if a user try accessing https://successtar.github.io/teamwork/foo, since it does not exist, GitHub will serve the 404.html page which has same content as the index.html and with this you get your react app working as expected.

Here is the source code for the example https://github.com/successtar/teamwork/tree/gh-pages

UPDATE

You can automate the process for every time you run npm run build to auto generate the 404.html file.

First Step: install shx for cross platform commands as follow npm install shx --save-dev

Second Step: Go to your package.json in the scripts block replace "build": "react-scripts build" with "build": "react-scripts build && shx cp build/index.html build/404.html"

That is all.

Whenever you run npm run build the 404.html file will be auto generated.

like image 95
successtar Avatar answered Oct 12 '22 01:10

successtar