You can display a custom 404 error page when people try to access nonexistent pages on your site.
GitHub Pages is available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see «GitHub’s products.»
-
On GitHub, navigate to your site’s repository.
-
Navigate to the publishing source for your site. For more information, see «Configuring a publishing source for your GitHub Pages site.»
-
Above the list of files, using the Add file drop-down, click Create new file.
-
In the file name field, type
404.html
or404.md
.
-
If you named your file
404.md
, add the following YAML front matter to the beginning of the file:--- permalink: /404.html ---
-
Below the YAML front matter, if present, add the content you want to display on your 404 page.
-
At the bottom of the page, type a short, meaningful commit message that describes the change you made to the file. You can attribute the commit to more than one author in the commit message. For more information, see «Creating a commit with multiple co-authors.»
-
If you have more than one email address associated with your account on GitHub.com, click the email address drop-down menu and select the email address to use as the Git author email address. Only verified email addresses appear in this drop-down menu. If you enabled email address privacy, then
<username>@users.noreply.github.com
is the default commit author email address. For more information, see «Setting your commit email address.»
-
Below the commit message fields, decide whether to add your commit to the current branch or to a new branch. If your current branch is the default branch, you should choose to create a new branch for your commit and then create a pull request. For more information, see «Creating a new pull request.»
-
Click Propose new file.
Further reading
- Front matter in the Jekyll documentation
Если вы получили 404 Page not Found
Когда вы публикуете свой сайт на GitHub Pages, то GitHub даёт вам ссылку вида https://USERNAME.github.io/REPONAME
, где USERNAME
— ваш ник на GitHub, а REPONAME
— название репозитория на GitHub, куда вы залили свой сайт.
Это ссылка только на сам репозиторий, в котором много файлов и GitHub не знает, какой из них нужно показать. Если бы в репозитории в корне лежал файл index.html
, то GitHub бы догадался и этот файл открылся бы по ссылке https://USERNAME.github.io/REPONAME
. Но если ваш index.html
где-то спрятан, например, в папке pages/
— Гитхабу нужно явно показать, где искать нужный .html
файл: https://USERNAME.github.io/REPONAME/pages/index.html
index.html
— это особое название для файла и GitHub Pages догадается показать его, даже если в ссылке его не указать: https://USERNAME.github.io/REPONAME/pages
.
GitHub обновляет сайт раз в 10 минут
Ответ об этом на SO. Если вы допустили какую-то ошибку и что-то поправили в файлах — придётся ждать целых 10 минут, чтобы подгрузилась исправленная версия
После каждого изменения в коде сайта ждите минимум 10 минут, прежде чем заходить на сайт и тестировать эти изменения. А лучше всего всё делать на своём компьютере и заливать на GitHub Pages уже готовую версию.
Если ссылки на сайте не открываются
Вам поможет статья про относительный адрес. Делайте ссылки относительными, а не абсолютными, чтобы сайту было всё равно где он хостится: хоть на 127.0.0.1, хоть на GitHub Pages. Если всё равно ошибка — и не получается написать правильный путь до файла — вот статья как это чинить
Попробуйте бесплатные уроки по Python
Получите крутое код-ревью от практикующих программистов с разбором ошибок и рекомендациями, на что обратить внимание — бесплатно.
Переходите на страницу учебных модулей «Девмана» и выбирайте тему.
In this article, I’ll be showing you how to create a custom error 404 page in GitHub Pages, a static site hosting service that allows you to publish and host your web pages through GitHub.
To break that down quickly: a static site is a website made up entirely of HTML, CSS, and JavaScript files. Everything the site needs to render is contained within these files, so there’s no need for server technology like PHP, Node.js, or Python. If the static site needs extra data from a server, it makes an asynchronous HTTP request with tools like fetch api
or axios
. And you’ll probably want to make sure that static site has a 404 page.
Displaying a 404 error page on your site is sort of like delivering bad news—the tone and manner of your delivery can determine if the person receiving the news will either be upset or be ready to agreeably look for another solution. Fortunately, GitHub Pages makes creating one a walk in the park.
How Does GitHub Pages Work?
Hosting your site on GitHub Pages is as easy as signing into GitHub and creating a new repository.
Your repo name should have the following format: <your github username>.github.io
.
Add files to your repo. You can do this either by creating the files locally and pushing to remote or by creating the files directly on GitHub.
Go to the Settings tab of your newly created repository.
Scroll down to the GitHub Pages section.
Here, you can choose the branch you want to serve your pages from, the root directory, and even select a Jekyll theme. If you already have a custom domain name, you can add it here.
By adding a custom domain name, you can access your site using yourdomainname
instead of your github.io
domain.
That’s all! Your site is now ready to be published. Visit <your github username>.github.io
to see your new website.
You can make changes to your site whenever you choose. They become available immediately after you push/merge to the branch you’ve chosen to serve your pages from.
Using GitHub Pages for your static site gives you some nice benefits:
- GitHub Pages is free to use. No coughing up extra cash just to host some basic web pages.
- You can use it to host websites like single-page applications or blogs.
- You can add a custom domain name to your site.
- You can enable HTTPS for your domain in just one click.
- You get the added advantage of managing your site with Git. Version-controlling your website becomes a piece of cake.
Why Is a 404 Page Important?
The 404 page is a famously dreaded sight across the internet. It’s a page that neither website users nor owners like to see, but it’s an unavoidable one. Its purpose is to inform a user that the page they’re looking for doesn’t exist.
Think about it: it isn’t every time you go into a store that you find everything you’re looking for. Certain items may be sold out or perhaps the store never sold them to begin with. That’s exactly what happens on the web. Perhaps the page’s URL changed, breaking an old link, or maybe the page was removed altogether. A user could have manually input the wrong URL to begin with. However a user has arrived at a particular URL, the requested web page doesn’t exist.
Specifically, 404 is an HTTP status code for a “Resource Not Found” or simply “Not Found” error. It applies to all kinds of resources on the web, including HTML files, CSS files, JavaScript files, documents, images, and just about any other file that could be requested from a server.
How you as the webmaster choose to convey a 404 error is very important. It can either improve your user’s experience on your site or make it worse.
What Makes a Good 404 Page?
At the end of the day, what’s on your 404 page is up to you, but I can give you a few tips to make it as palatable as possible for your users:
- First and foremost, a 404 page should return with an actual 404 HTTP status code. This is important so web crawlers like Google’s bot don’t incorrectly index an erroneous page as a valid page, as this can negatively impact your SEO.
- The 404 page should make it clear to the user that there’s a problem. This can be achieved by making the 404 or Not Found message prominent on the page.
- The page should offer a way out to the user. Unless you want the user stuck on your error page or want them to close your site immediately, your 404 page should provide them with a means to navigate away from the page. Add an obvious link to your site’s homepage to somewhere on the error page, or you can suggest links to pages that might be similar to what the user was looking for in the first place.
- You can provide a way for users to report a broken page, enabling you to quickly fix any issues.
- Add a search bar for users to find other things they might be looking for.
- Make the design pleasing to the eye. A 404 page is still a part of your website, so you should put as much thought into its design as you have for other valid pages. The page should carry elements of your brand, and not look like a desert island.
GitHub’s very own 404 page is a good example of what a 404 page should look like. The error code and message are both prominent on the page, and there’s a search bar to help you find other content.
If you don’t add a custom 404 page to your GitHub Pages site, then by default GitHub displays the following 404 page:
Not bad, eh? But not good enough for your brand.
How to Create a Custom 404 Page in GitHub Pages
Fortunately, GitHub also understands the importance of a 404 error page, and provides developers an easy way to add one to their GitHub-hosted pages. Let’s look at how you can add your own custom 404 page.
Create a new file in the root of your repository and name it 404.html
.
Then go on to add content for the 404 page as follows:
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Page Not Found</title><linkrel="preconnect"href="https://fonts.gstatic.com"><linkhref="https://fonts.googleapis.com/css2?family=Chango&family=Roboto:[email protected]&display=swap"rel="stylesheet"><style> body{background-image:url("https://images.unsplash.com/photo-1616235132417-99f443954d2e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=334&q=80");background-size:cover;font-family:'Roboto','sans-serif';} main{display:flex;height:100vh;justify-content:center;align-items:center;flex-direction:column;} .header404{font-family:'Chango',cursive;font-size:48px;} .content404{text-align:center;}</style></head><body><main><h4class="header404">404</h4><divclass="content-404"> Uh-oh! We couldn't find the page you are looking for. </div><p><ahref="/">Check our home page</a></p></main></body></html>
Enter fullscreen mode
Exit fullscreen mode
Commit your changes, then try to visit a page that doesn’t exist on your site, eg,username.github.io/a-random-page-that-doesn't exist
. A page like this should appear:
Conclusion
Hopefully, this article has shed some light on the importance of a 404 page and why you should put some effort into branding it as you would other pages of your website. When properly done, a 404 error page can be a good way to increase your website’s conversion rate.
Unlike many other host servers where you have to tinker with .htaccess
or other kinds of configuration settings to handle 404 error pages, GitHub Pages makes it incredibly easy. All you need to do is add a single file, and you’re good to go.
If you’re stuck for ideas on what your 404 error page can look like, you can always look around for some 404 inspiration.
By Sodeeq Elusoji
The project structure of a Blazor WASM project is in some places very different than other frontend frameworks in the .NET stack. One of the nice things about Blazor WASM is that it can be hosted by any static file host. A problem with this is that routing is handled in many different ways on different hosts. In this article, we will look at the 404
error that often occurs when accessing a route directly on a GitHub Pages hosted Blazor WASM page and how to fix it.
The problem
Previously we have often used the IIS to host our websites and managed routing and error handling through the web.config
file. We can’t do this when using static file hosts. GitHub Pages is not configured to support SPA (Single Page Application) routing out of the box, but we can make some changes to our project to make it work.
First, we need to see when the problem occurs. If we have some Blazor WASM page that is hosted on GitHub Pages that uses routing meaning that it has more than one page. Then we might have an URL like the following:
https://myaccount.github.io/MyProject/MyPage/
We can nicely go to this page using the navigation in the website or when we run the project locally. But if we try to access this URL directly we will be faced with the following page.
404
File not found
The site configured at this address does not contain the requested file.
If this is your site, make sure that the filename case matches the URL.
For root URLs (like http://example.com/) you must provide an index.html file.
The reason
The problem occurs because of how GitHub Pages serves files. If it sees something that looks like a directory in the URL after the expected https://myaccount.github.io/MyProject/
then it will assume that you have some folder e.g. /MyPage
that has an index.html
file available to serve. We don’t actually have a directory for /MyPage
as it is just a route that we have defined in Blazor to make the experience of using the website better for the user.
The solution
The solution consists of two parts. First, we will need to redirect the user to some known page where we can control their further navigation. And then we will need to tell the Blazor WASM website where the user actually wanted to go.
We catch the user by creating a file called 404.html
in the wwwroot
folder of the project which is what gets published when using GitHub Pages to host. GitHub Pages automatically redirects users to this page instead of the screen we saw earlier. It shows this page but maintains the same URL which we can then extract and use to recover the state. The content of the 404.html
is the following:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Single Page Apps for GitHub Pages</title>
<script type="text/javascript">
// Single Page Apps for GitHub Pages
// MIT License
// https://github.com/rafgraph/spa-github-pages
// This script takes the current url and converts the path and query
// string into just a query string, and then redirects the browser
// to the new url with only a query string and hash fragment
// If you're creating a Project Pages site and NOT using a custom domain,
// then set pathSegmentsToKeep to 1 (enterprise users may need to set it to > 1).
// This way the code will only replace the route part of the path, and not
// the real directory in which the app resides, for example:
// https://username.github.io/repo-name/one/two?a=b&c=d#qwe becomes
// https://username.github.io/repo-name/?/one/two&a=b~and~c=d#qwe
// Otherwise, leave pathSegmentsToKeep as 0.
var pathSegmentsToKeep = 1;
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>
This comes from the GitHub repository https://github.com/rafgraph/spa-github-pages which is a repository that contains some general useful files for using SPA frameworks on GitHub Pages.
Now we have been redirected to the index.html
file and all paths, query strings, and hashtags (anchor links) have been passed on. The query strings are combined in a single query string called q
and the paths are placed in a query string called p
.
We then need to decode these query strings and navigate to the correct page. This is done with the following code snippet that we will need to place in the head of our index.html
file (the earlier the better).
<script type="text/javascript">
// Single Page Apps for GitHub Pages
// 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>
It navigates to the correct page by setting the state directly using the window.history.replaceState
API. This sets the state that Blazor WASM uses internally to keep track of which page you are on.
Conclusion
Now we have seen when the 404 error happens in a Blazor WASM project hosted on GitHub Pages. We have explored why it happens. And in the end, we have seen a solution for the problem which it shares with other SPA frameworks on GitHub Pages.
If you have any questions about the content of this article or comments then feel free to reach out.
elmah.io: Error logging and Uptime Monitoring for your web apps
This blog post is brought to you by elmah.io. elmah.io is error logging, uptime monitoring, deployment tracking, and service heartbeats for your .NET and JavaScript applications. Stop relying on your users to notify you when something is wrong or dig through hundreds of megabytes of log files spread across servers. With elmah.io, we store all of your log messages, notify you through popular channels like email, Slack, and Microsoft Teams, and help you fix errors fast.
See how we can help you monitor your website for crashes
Monitor your website