nginx |
Apache HTTPD |
Lighttpd |
express.js |
koa.js |
Caddy |
Customization
Simple HttpErrorPages
Simple HTTP Error Page Generator. Create a bunch of custom error pages — suitable to use with Lighttpd, Nginx, expressjs, koajs ,Apache-Httpd or any other Webserver.
Features
- Static pages (for webservers)
- Multi-Language (i18n) support
- Generator script to customize pages
- Native express.js middleware
- Native koa.js middleware
Demo
- HTTP400
- HTTP401
- HTTP403
- HTTP404
- HTTP500
- HTTP501
- HTTP502
- HTTP503
- HTTP520
- HTTP521
Download
Just clone/download the git repository or use the prebuild packages (only the generated html files are included)
Download Prebuild Packages (Pages only, en_US)
- Download Single Files
NGINX Integration
NGINX supports custom error-pages using multiple error_page
directives.
File: default.conf
Example — assumes HttpErrorPages are located into /var/ErrorPages/
.
server { listen 80; server_name localhost; root /var/www; index index.html; location / { try_files $uri $uri/ =404; # add one directive for each http status code error_page 400 /ErrorPages/HTTP400.html; error_page 401 /ErrorPages/HTTP401.html; error_page 402 /ErrorPages/HTTP402.html; error_page 403 /ErrorPages/HTTP403.html; error_page 404 /ErrorPages/HTTP404.html; error_page 500 /ErrorPages/HTTP500.html; error_page 501 /ErrorPages/HTTP501.html; error_page 502 /ErrorPages/HTTP502.html; error_page 503 /ErrorPages/HTTP503.html; } # redirect the virtual ErrorPages path the real path location /ErrorPages/ { alias /var/ErrorPages/; internal; }
Apache Httpd Integration
Apache Httpd 2.x supports custom error-pages using multiple ErrorDocument directives.
File: httpd.conf
or .htaccess
Example — assumes HttpErrorPages are located into your document root /var/www/...docroot../ErrorPages
.
ErrorDocument 400 /ErrorPages/HTTP400.html ErrorDocument 401 /ErrorPages/HTTP401.html ErrorDocument 403 /ErrorPages/HTTP403.html ErrorDocument 404 /ErrorPages/HTTP404.html ErrorDocument 500 /ErrorPages/HTTP500.html ErrorDocument 501 /ErrorPages/HTTP501.html ErrorDocument 502 /ErrorPages/HTTP502.html ErrorDocument 503 /ErrorPages/HTTP503.html
Lighttpd Integration
Lighttpd supports custom error-pages using the server.errorfile-prefix directive.
File: lighttpd.conf
Example — assumes HttpErrorPages are located into /var/www/ErrorPages/
.
server.errorfile-prefix = "/var/www/ErrorPages/HTTP"
expressjs Integration
HttpErrorPages are available as NPM-Package — just install http-error-pages
via npm/yarn
Installation
yarn add http-error-pages
Example
A ready-to-use example can be found in examples/express.js
const _express = require('express'); const _webapp = _express(); const _httpErrorPages = require('http-error-pages'); async function bootstrap(){ // demo handler _webapp.get('/', function(req, res){ res.type('.txt').send('HttpErrorPages Demo'); }); // throw an 403 error _webapp.get('/my403error', function(req, res, next){ const myError = new Error(); myError.status = 403; next(myError); }); // throw an internal error _webapp.get('/500', function(req, res){ throw new Error('Server Error'); }); // use http error pages handler (final statement!) // because of the asynchronous file-loaders, wait until it has been executed await _httpErrorPages.express(_webapp, { lang: 'en_US', payload: { footer: 'Hello <strong>World</strong>', myvar: 'hello world' } }); // start service _webapp.listen(8888); } // invoke bootstrap operation bootstrap() .then(function(){ console.log('Running Demo on Port 8888'); }) .catch(function(e){ console.error(e); });
Options
Syntax: Promise _httpErrorPages.express(expressWebapp [, options:Object])
template
(type:string) — the path to a custom EJS template used to generate the pages. default assets/template.ejscss
(type:string) — the path to a precompiled CSS file injected into the page. default assets/layout.csslang
(type:string) — language definition which should be used (available in thei18n/
directory). default en_USpayload
(type:object) — additional variables available within the templatepayload.footer
(type:string) — optional page footer content (html allowed). default nullfilter
(type:function) — filter callback to manipulate the variables before populated within the templateonError
(type:function) — simple debug handler to print errors to the console (not to be used in production!)
koajs Integration
HttpErrorPages are available as NPM-Package — just install http-error-pages
via npm/yarn
Installation
yarn add http-error-pages
Example
A ready-to-use example can be found in examples/koa.js.
Keep in mind that the following example has to be executed within an async context!
const _koa = require('koa'); const _webapp = new _koa(); const _httpErrorPages = require('http-error-pages'); // use http error pages handler (INITIAL statement!) // because of the asynchronous file-loaders, wait until it has been executed - it returns an async handler _webapp.use(await _httpErrorPages.koa({ lang: 'en_US', payload: { footer: 'Hello <strong>World</strong>', myvar: 'hello world' } })); // add other middleware handlers _webapp.use(async (ctx, next) => { if (ctx.path == '/'){ ctx.type = 'text'; ctx.body = 'HttpErrorPages Demo'; }else{ return next(); } }); // start service _webapp.listen(8888);
Options
Syntax: Promise _httpErrorPages.koa([options:Object])
template
(type:string) — the path to a custom EJS template used to generate the pages. default assets/template.ejscss
(type:string) — the path to a precompiled CSS file injected into the page. default assets/layout.csslang
(type:string) — language definition which should be used (available in thei18n/
directory). default en_USpayload
(type:object) — additional variables available within the templatepayload.footer
(type:string) — optional page footer content (html allowed). default nullfilter
(type:function) — filter callback to manipulate the variables before populated within the templateonError
(type:function) — simple debug handler to print errors to the console (not to be used in production!)
Caddy Integration
Caddy supports custom error-pages using errors
directive.
File: Caddyfile
Example — assumes HttpErrorPages are located into /var/www/error
.
www.yoursite.com {
// Other configurations
errors {
404 /var/www/error/HTTP404.html
}
// Other configurations
}
Customization
First of all, clone
or download the http-error-pages repository.
Install Dependencies
You have to install the node dev dependencies to build the pages:
# run the yarn command within the cloned repository yarn install # or if you more familiar with npm.. npm install
To customize the pages, you can edit any of the template files and finally run the generator-script.
All generated html files are located into the dist/
directory by default.
If you wan’t to add custom pages/additional error-codes, just put a new entry into the i18n/pages-en_US.json
file (its recommended to copy the file).
The generator-script will process each entry and generates an own page.
Files
- config.json — basic configuration options
- assets/layout.scss — the SCSS based styles
- assets/template.ejs — the EJS based page template
- i18n/pages-.json — the page definitions (multilanguage)
- dist/*.html — generator output directory
Change page styles
To modify the page styles, just edit the SCSS based layout assets/layout.scss and finally run gulp to generate the css code.
The new layout file is stored in assets/layout.css — run the page generator to create the pages.
Example
# start gulp sccs via npm $ npm run gulp > http-error-pages@0.6.0 gulp HttpErrorPages > gulp [08:40:33] Using gulpfile HttpErrorPages/gulpfile.js [08:40:33] Starting 'sass'... [08:40:34] Finished 'sass' after 108 ms [08:40:34] Starting 'default'... [08:40:34] Finished 'default' after 40 μs # generate http-error-pages using modified stylesheet $ npm run static > http-error-pages@0.6.0 static HttpErrorPages > node bin/generator.js static Paths |- Config: HttpErrorPages/config.json |- Template: HttpErrorPages/assets/template.ejs |- Styles: HttpErrorPages/assets/layout.css |- Pages: HttpErrorPages/i18n/pages-en_US.json Generating static pages |- Page <HTTP404.html> |- Page <HTTP403.html> |- Page <HTTP400.html> |- Page <HTTP500.html> |- Page <HTTP501.html> |- Page <HTTP502.html> |- Page <HTTP520.html> |- Page <HTTP503.html> |- Page <HTTP521.html> |- Page <HTTP533.html> |- Page <HTTP401.html> Static files generated
Multi language (i18n)
To use a different language just provide a custom page definition — in case the file is located in i18n
you can use the --lang option
Example
$ npm run static -- --lang pt_BR
> http-error-pages@0.6.0 static HttpErrorPages
> node bin/generator.js static "--lang" "pt_BR"
Paths
|- Config: HttpErrorPages/config.json
|- Template: HttpErrorPages/assets/template.ejs
|- Styles: HttpErrorPages/assets/layout.css
|- Pages: HttpErrorPages/i18n/pages-pt_BR.json
Generating static pages
|- Page <HTTP404.html>
|- Page <HTTP400.html>
|- Page <HTTP401.html>
|- Page <HTTP403.html>
|- Page <HTTP500.html>
|- Page <HTTP501.html>
|- Page <HTTP502.html>
|- Page <HTTP520.html>
|- Page <HTTP503.html>
|- Page <HTTP521.html>
|- Page <HTTP533.html>
Static files generated
Add custom pages
Create custom error codes/pages used by e.g. CloudFlare
Example
// webserver origin error "520": { "title": "Origin Error - Unknown Host", "message": "The requested hostname is not routed. Use only hostnames to access resources." }, // webserver down error "521": { "title": "Webservice currently unavailable", "message": "We've got some trouble with our backend upstream cluster.nOur service team has been dispatched to bring it back online." },
Change footer message
The footer message can easily be changed/removed by editing config.json.
Example — customm footer
{ // Output Filename Scheme - eg. HTTP500.html "scheme": "HTTP%code%.html", // Footer content (HTML Allowed) "footer": "Contact <a href="mailto:info@example.org">info@example.org</a>" }
Example — no footer
{ // Output Filename Scheme - eg. HTTP500.html "scheme": "HTTP%code%.html" }
Placeholders/Variables
The following set of variables is exposed to the ejs template (404 page example):
{ title: 'Resource not found', message: 'The requested resource could not be found but may be available again in the future.', code: '404', language: 'en', scheme: 'HTTP%code%.html', pagetitle: "We've got some trouble | %code% - %title%", footer: 'Tech Contact <a href="mailto:info@example.org">info@example.org</a>', myvar: 'Hello World' }
To generate dynamic titles/content based on the current variable set, each variable is exposed as placeholder
(surrounded by %
).
You can also define custom variable within the page definitions, everything is merged togehter.
Modify the HTML template
The HTML template is based on ejs and located in assets/template.ejs — you can apply any kind of changes.
<!DOCTYPE html> <html lang="<%= vars.language %>"> <head> <!-- Simple HttpErrorPages | MIT License | https://github.com/HttpErrorPages --> <meta charset="utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1" /> <title><%= vars.pagetitle %></title> <style type="text/css"><%- vars.inlinecss %></style> </head> <body> <div class="cover"><h1><%= vars.title %> <small><%= vars.code %></small></h1><p class="lead"><%= vars.message %></p></div> <% if (vars.footer){ %><footer><p><%- vars.footer %></p></footer><% } %> </body> </html>
Command line options
The http-error-pages generator allows you to use custom template/config files directly. This is the recommended method to create full-customized pages.
$ npm run static -- --help
> http-error-pages@0.6.0 static HttpErrorPages
> node bin/generator.js static "--help"
Usage: static [options] [config]
run http-error-pages generator
Options:
-t, --template <path> path to your custom EJS template file
-s, --styles <path> path to your custom stylesheet (precompiled as CSS!)
-p, --pages <path> path to your custom page definition
-l, --lang <lang> the language of the default page definition
-o, --out <path> output directory
-h, --help output usage information
Example — use custom files
We assume you’ve created a folder named example_org
which contains all relevant template files
# via npm run-script (cross platform) $ npm run static -- -t example_org/template.ejs -s example_org/styles.css -p example_org/pages.json -o example_org/output # .. or directly (linux only) $ http-error-pages -t example_org/template.ejs -s example_org/styles.css -p example_org/pages.json -o example_org/output
License
HttpErrorsPages is OpenSource and licensed under the Terms of The MIT License (X11) — your’re welcome to contribute
Whether you need inspiration or want to save time, these best free error page templates will do you well. All are easy to use, ensuring you get the most out of them quickly and comfortably.
The five most common website errors you get are 400 for bad request, 401 for unauthorized, 403 for forbidden error, the most common 404 for page not found, and 500 for internal server error. Among all these error pages, the most frequent error page template you get pre-bundled with your website template is 404.
We have also made a separate collection of the best free error page templates, of which many are hand-crafted by the Colorlib team. In addition to that, you also get very many other alternatives, making sure this collection has something for everyone.
Since free error page templates are easy to customize, use these as a base to create your custom error page. Before getting into the list, all the free templates mentioned here are raw. Use them for inspiration or style them further, the options are very many.
Colorlib 404 Customizer (WordPress plugin)
This is the only WordPress plugin that made a list. It is effortless to use, and has a great design, templates, and customization options.
More info / Download
Colorlib 404 v1
If you are running your own online business, your website needs to have a 404 page. Not just any type, make it unique and original, just like your main website is. Instead of using a default one, enhance things with any free error page templates that you can utilize right off the bat. They are simple to employ, modern, mobile-ready, and appealing to the eye. You can also fine-tune them and lightly customize the web design to get it to match your branding. It does not always have to be complicated adding new layouts to your existing or soon-to-be-ready-for-launch website.
More info / Download Demo
Colorlib 404 v2
You can keep the basic look and still get things going strong online with your error page. No need to overcomplicate, simplicity is always the winning approach if you do not know yet what would fit your project best. And to attain fantastic results, this cracking-free error page template is more than ideal. What’s cool about this layout is that instead of just featuring the 404 sign, it also has a search bar. This way, you can give your user another chance to find what they are looking for before leaving your page. Have no call-to-action button, and there is a good chance they will simply close the page and search elsewhere.
More info / Download Demo
Colorlib 404 v3
If the purest simplicity with a touch of creativity is what you strive for, we have a neat little treat for you. A stunning, catchy, responsive, and flexible black and white free error page template will do the trick. If you are already rocking a minimal look with your website, keep it intact even when it comes to a 404 page. You can do that easily right now by downloading the template and putting it to use straight away. With this cracking look, you probably won’t even want to change anything just use it exactly as is.
More info / Download Demo
Colorlib 404 v4
Another simple free error page template with just the right action will keep your users engaged. And, instead of leaning toward leaving your page, they can simply hit the Go To Homepage button and continue enjoying your content. Indeed, that is exactly what you want them to do. With a vibrant and inviting call-to-action button, you can increase your potential and prevent the likelihood of them bouncing off. You can also play around with trying out different tweaks and creating a brandable error page. Use your creativity and enrich it with your signature touch if even necessary.
More info / Download Demo
Colorlib 404 v5
If the page they are looking for no longer exists, you can redirect the URL or simply use an error page. There is a good chance they also end up typing a wrong search query that will lead them to a 404 error page. Whatever the case, you can keep their engagement at the highest degree even if they land on a page without any result. You can offer them to go back or let them search again with the search function. Yes, you can have it all featured on a 404 page, and this free page template has it already predesigned for you.
More info / Download Demo
Colorlib 404 v6
If your website follows a dark layout, it is obvious that you would want your error page to be of the same style. Build it yourself, however, what would be even better is to download this design simple and you are ready to rock. A stunning, elegant, and sophisticated free error page template with nice attention to detail. On top of that, it also sports a homepage call-to-action button to redirect all your visitors back to your index page in just a click. You can now keep your website’s theme intact and of the highest degree, even when it comes to a 404 page.
More info / Download Demo
Colorlib 404 v7
Regardless of the style, you rock with your page, we have a free error page template. No need to build one from the ground up anymore when you have so many different variations and solution at the tip of your fingers. We could call this next one a bubbly error page, what do you say? Instead of letting them leave the page right away, encourage them to find what they were seeking for in the first place. With rounded typography and pink for its core color, you will keep their attention and have them type in the search query once again. The page has a search bar and a Return To Homepage button for your information.
More info / Download Demo
Colorlib 404 v8
Another free error page template with a beautiful dark layout for everyone who would like to go against the norm. Sure, pages with light designs are more popular, but some folks prefer a dark layout. They fancy it because a website with a dark layout gives them better results. Anyhow, grab yourself this neat and modern, as well as mobile-ready and flexible, site skin and introduce it to your website without hassle. Let them know what caused them to end up on a 404 page and offer them to go back to your home page with just one click.
More info / Download Demo
Colorlib 404 v9
Sometimes, you see some text, the other time an icon and the third time, they use an entirely custom design for an error page. Whoever is in the process of bringing into being a must-have website as fast as possible, help yourself with free ready-to-use layouts. You know that you have loads of free error page templates to choose from that will save you extra time. Here is a cool, simple and easy to use web design that you can use at free will. You can also edit the text if you want to share a different message and even have the hover effect call-to-action button send it to your blog instead of the home page.
More info / Download Demo
Colorlib 404 v10
One thing is for sure, you would want to keep your branding flowing at the same level of sophistication across your entire web space. Get a free template now and put it to use right away. Make it striking and exciting even when it comes to a simple error page. As for the error page, we bring you a vast collection of different solutions that will, in many cases, suit your needs out of the box. Give them an “Oops!” and then lead them back to your compelling home page to find what they were looking for.
More info / Download Demo
Colorlib 404 v11
This free error page template can be a great extension to your already impressive photography website. The template features an image background with an overlay 404 notice, search bar, call-to-action button and social media buttons. On the flipside, you can also use it for an assortment of projects that you already run or plan to start. Indeed, a lot is going on on this web design, yet still, the experience will be outstanding. Download it now, take it to your advantage and keep your visitors excited even if they accidentally land on the 404 page.
More info / Download Demo
Colorlib 404 v12
A crying emoji works more than ideal to have fun with your error page. On top of that, this free template is versatile and adaptive enough to work with numerous projects, whether a blog, a music platform or an agency page. While you will likely want to keep the catchy 404 notice, you can freely modify the text and the call-to-action button. The latter, you can link with your home page or take your users to a different section of your website, that is totally up to you. Whatever your final product looks like, it is a guarantee that will do the trick.
More info / Download Demo
Colorlib 404 v13
Cool sign and vibes are what’s up when you pick this free error page template for your website. You will just want to download it and add it to your page for the most part. It is a smart layout that works great with pretty much any website. The choice of fonts makes it appear a tad more fun and jolly what keeps their engagement at the highest degree. Besides, you can also alter the text and the CTA (call-to-action) button and share a custom message if necessary. You read that right, there is also a button in red and can take them back to the home page. After all, you do not want to lose your visitors even if they landed on an error page.
More info / Download Demo
Colorlib 404 v14
While 404 error pages are simple looking for the most part, you can still take an extra step and add creativity to them. A simple OOPS!, some extra wording, GO BACK button and social media icons in a fun cloud is all it takes to make the design appear more charming. Just take this free error page template as a fantastic example of my previous saying.
More info / Download Demo
Colorlib 404 v15
Shave all the possible distractions off the web design or keep things more engaging with animations, whatever the case, we have things sorted out for you. With many free error page templates at your services, you can add just about any type of layout to your page as you wish. If you need something more than v15 is the exact tool that you should go and download right now. It is an attractive 404 page with included homepage button, social media icons and animations. The positive impact, it will have on your users, will surely be rewarding.
More info / Download Demo
Colorlib 404 v16
Either you have a lot of red on your website or you would just like to strike them heavy, here is the right free error page template for you. As you see it for yourself, it is a beautiful 404 sign that will immediately let them know that they are on the wrong page of your website. On such that is not even available. No problem, you can easily maintain their presence by offering them to go back to the index page or straight up contact you. In addition, you can also promote your social media platforms with integrated buttons.
More info / Download Demo
Colorlib 404 v17
With a cool error page, you can let your users know that what they are searching for is no longer available or never was in the first place. Sometimes, the wrong search query leads them to the error page. However, you might do a large website update that makes you remove some of the pages in other cases. Whatever the situation, ensure that you keep your expertise consistent and of the highest standards even when it comes to an error page. An easy-to-use and implement free error page template will greatly value your webspace.
More info / Download Demo
Colorlib 404 v18
If you miss a page or the keyword they typed in the search bar is irrelevant, the error page will appear. Keep the default one or spice things up with a more catchy, cool, and fashionable layout. You can now get multiple free error page templates and test things out before you call it a day. It is unnecessary, but having a button that leads the user back to the home page can benefit. At least they might not leave your page immediately and continue browsing your site’s content.
More info / Download Demo
Colorlib 404 v19
When you have a page on your website that is no longer available or you changed the name, a 404 page will occur. What to do with the error page is entirely up to you. However, we advise you to make it cool and actionable, helping you keep your users around for longer. With a simple notice and a link back to the home page, they might take action first instead of leaving your website. Moreover, you can also feature social media buttons and let them take a peek at what’s hot over there. This free error page template has both Return to homepage link and social icons for your convenience.
More info / Download Demo
Colorlib 404 v20
Everyone who ends up on a 404 error page, you should make sure they do not leave and visit your competitor’s page. Instead, at least give them a quick option to go to your home page where they can continue skimming through your content, products or services. If they have nothing to click on, they might simply quit your site and move forward. Make sure that is not the case for you. For your own good sake, you should do whatever it takes to have them engaged at all times. And when it comes to error pages, you have loads of modern, professional and stunning alternatives just a click away.
More info / Download Demo
Error Page 404 Vampire
If you want a fun way to display your error pages, you better go with this cute vampire version. It features a moving head of a vampire with blood dripping out his mouth sandwiched between a four and a four. Below is some text you can alter and further down a call-to-action button.
You can use this free error page template or add your personal touch. Make it follow your branding so it does not feel weird when visitors land on it. Otherwise, it might feel like they are not on your page anymore and will leave it altogether. Do things creatively and fun, go against the norm, and stand out from the crowd, even with error pages.
More info / Download Demo
404 Error
This next one will get you clicking. If nothing else, then the back button for sure. However, you might also start hitting the delete key because the animation is just too enticing and persuasive. The free 404 Error page template is a cartoon of a black and white finger repeatedly pressing the delete button on a keyboard. Unfortunately, there is no call-to-action button that this template offers.
However, the tool uses HTML and CSS if you want to tweak customization and enhance its presentation. You might add your own CTA or encourage visitors to return to where they came from if your website led them to an error page. For whatever reason, these on-repeat short clips hook you every single time and make you stare at them with your eyes bulging.
More info / Download Demo
Error Occurred
Error Occurred is a 500 error page template. With the animated web elements and the background, this template provides an interactive experience to the users. Simple clean texts are used to show the message to the users and a single line space is given to help you give a personalized message to the user. You also can add your logo to the center of the page.
To demo the code the user uses the freelancer website logo. The template uses a blue color scheme to meet the design consistency, but you can change the color to your brand color if needed. Since you gave clear instructions to reload the page, you don’t get any call to action buttons with this error page template. The template uses HTML5 and CSS frameworks.
More info / Download Demo
Unicorn
You no need to be creative only with the design and the visual effects. You can also make use of the words to stay creative. But this 404 error page template gives you both simple creative design and ample space to add a creative message.
The unicorn image took the major space on this design. You can use your brand character here instead of the unicorn if you have any character like the Edd with the Easy digital download or one-eyed monster with the Optinmonster. At the bottom you have a call to action button to take the user to the previous page.
More info / Download Demo
Under Maintenance
This error page template can be used for scheduled maintenance when your site is down. With the simple animation and fewer option this template only uses few lines of code. So the template is lightweight and has plenty of room for improvement if you need. Other than the animated image and few lines of texts there are no other elements on this template. If you wish, you can customize this template to fit your need. Some big websites will maintain only certain parts of the website by leaving other pages to give users an uninterrupted service. If you are also doing so, you can add other working web page links to this error page template to retain the visitor.
More info / Download Demo
404 Crying Baby
404 Crying baby is another character based animation error page template. This is a 404 error page template, it looks clean and pixel perfect. The animation effects are smooth, each element are neatly animated with no lag or overlap. The bold white 404 text is clearly legible on the clean solid blue background. This template does not give you any space for adding personal messages or other web elements like the call to action button. If you need to customize this template, it uses HTML and CSS frameworks.
More info / Download Demo
Bill Error Page
It is a perfect choice for both personal website templates and business website templates. This template fills the screen space with bold 404 texts and a neat animated character in the full-width design. The character and background alignment is done perfectly to fit within the zero of the 404. Another interactive element with this template is a hover text showing the character name. You can use this space for adding a text link to other pages. Again if you have any brand character, you can use it here to make your website reflect your brand consistently throughout the design.
More info / Download Demo
Lost in Space
Lost in space is a complete package. This well-coded error page template uses HTML, CSS3, and Javascript framework. This template ticks all the boxes to create a perfect error page template. It is a full-width website template that smartly manages the screen space with an animated background, giving the template a lively feel. This template is fully functional and has all the necessary features you need. You can mention the error code and give enough space to add your custom message. At the bottom, you can add a call to action button to take the visitors to the homepage.
More info / Download
404 Gradient
404 gradient is a simple and elegant modern error page template. Most of the HTML website templates include 404 templates with the package. Nowadays, even some premium quality free website templates include all the basic pages designed for you. If you are unsatisfied with the pre-bundled 404-page template, you can use creative templates like this 404 gradient.
With this template, you can clearly state the error to the user and have a small space to add your personal message. The call to action button at the bottom can take the user to the homepage or the previous page.
More info / Download Demo
Error Page #2
Error Page #2 is a light-colored error page template. The animation effects are also designed with a dark to light color transformation to match its light color. It is also a 404 error page template since the code is shared with you directly you can change it to make this work for other errors. This template is also a complete error page with pixel-perfect design and useful features like the lost in space. With this template, you get one line space to add a custom message and a call to action button at the bottom. This template is purely developed with the latest HTML and CSS framework.
More info / Download Demo
Swinging 404
This error page template is the best match for the kindergarten website templates. Because the mild colors and attractive minimal animation effects of this error page template can blend well with the school website templates. Apart from the visual effects, every other feature remains the same as you have seen in Error page #2 and the 404 gradient error page template. At the bottom, you can add a call to action button to take the users to the homepage or the previous page. Again it is a clean template that only uses the latest HTML and CSS frameworks.
More info / Download Demo
Torch Not Found
It is an interactive template is a clean visual effect. Searching with torch animation is used in this template to match the page not found meaning logically. With this template, you can directly notify the user of the error code and the page not found error message. This template did not give you any other option to help you add a personal message; it is an obvious choice because for this type of animated template, even if you add any personal message, mostly users won;’t stay on the page to see the message.
More info / Download Demo
Error Page With Animation
Here is a neat free error page template with great creativity. Instead of keeping the 404 page dull, have fun with this template. To some extent, it is pretty basic, still, it has a neat animation that will trigger everyone’s interest. Moreover, you can also fine-tune and adjust the entire template so it seamlessly fits your website’s theme.
More info / Download Demo
Chrome’s Internet Connection Error
Is that what you have been looking for? Or would you just like to add something different that everyone will instantly recall from back in the day? Anyhow, here is a free template that you can use for an error page featuring a pixelated dinosaur and text. Of course, you have the right to style the default configurations so they match your design. You will also notice that the text appears/disappears on hover.
More info / Download Demo
Cool 404 Error Page
Scary eyes watching you and all over the place, that’s what’s up when it comes to this free error page. It is one of those cooler ones, helping you add a touch of fun to your website – because, why not? Needless to say, if you would like to improve something, like text, for instance, you are welcome to do it using the online editor directly. Play with the functions and create a precise outcome to your liking.
More info / Download Demo
Closed
You might need to check this template if you are searching for a creative error page template for a restaurant website template or any other related template related to the store. The bright color and subtle animation notify the user that some error has occurred. At the top, you have the option to add your social profile link and a link to the contact details. If the website template uses any other color scheme, you can change this template’s bright yellow color to your default website color scheme. This template is developed purely on the HTML and CSS frameworks.
More info / Download Demo
Glitch Effect
Glitch Effect is one of the trending design trends in the visual industry. Now it is slowly making its way to the web design world. With modern web development, we can make a perfect glitch effect that looks surreal. Again this template is just a base, you have to develop your error page. In the features wise also you don’t get any options. To say it, this template just shows the 404 error message directly to the users.
More info / Download
SVG Animation
SVG Animation is another animated 404 error page template. If you wish to stay creative only with the visual effects, you can use this template. But you have plenty of white space in this full-width design layout. So you can customize and use this space to add any other useful links or a search bar option.
The SVG animation template uses HTML, CSS, and Javascript frameworks. Since this template prioritizes the visual effects, you have well-coded Javascript and only a few lines of CSS. This template is not mobile responsive. Overall if you intended to use this template, make it clear you can’t use this directly, you have to build your error page over this code.
More info / Download Demo
404 error page, Caveman mode
An terrific free error page template featuring two troglodytes hitting each other on the head with a club. Even if your page is clean and minimalistic, you can always level things up with an engaging error page. This one is a perfect alternative that will do the trick. It is so cool that it does not need any customization or whatnot. Just use it as is. But be careful, your visitors might love it so much, they will want to land on the error page on purpose. Anyway, enjoy using it and implementing it into your web space.
More info / Download Demo
404 error page
Another fantastic 404 error page, featuring two adventurists investigated the 404 sign with lamps. It sure is dark over there. A cool animation on the number zero, the lamps and making it feel like it is floating will definitely trigger everyone’s interest. While you would want to avoid getting folks to land on an error page, you would definitely want to make it as fun as possible when they do. However, to each their own. You have many designs and creations here that will definitely do the trick regardless of your taste. And they are free, so you can test a bunch of options before deciding on the winner.
More info / Download Demo
Photo Error
This error page template is a design inspiration for the photography website template and the directory website templates. Instead of a static background, this template uses animated photos falling effect. You can use this part to show your best clicks even on the error page. But the problem is you must get your hands dirty to make this template as you wish. Without customizations, you can’t make a personal impression with this error page template. Another useful feature with this template is a call to action button to take the user to the homepage and hover effects.
More info / Download Demo
What Will be Your Design Inspiration
These are some of the best free error page templates you can use as a design inspiration to create your custom error pages. Most of the templates in this list share the code they used to help you get even better idea on how they work. If you are a developer, this free error template will be a base model to create your custom template for your web projects. Still can’t find the template you want? Please look at our other template collections to get a better idea.
Hello Friends, In this article I have listed 35+ Best HTML CSS 404 Page Templates which are available on CodePen.
Best Collection of 404 error page design
#1: 404 Page – Lost In Space
404 Page – Lost In Space, which was developed by Saleh Riaz Qureshi. Moreover, you can customize it according to your wish and need.
Author: Saleh Riaz Qureshi
Created on: April 23, 2018
Made with: HTML, CSS & JS
Tags: 404 Page Lost In Space
#2: 404 SVG animated page concept
404 SVG animated page concept, which was developed by Volodymyr Hashenko. Moreover, you can customize it according to your wish and need.
Author: Volodymyr Hashenko
Created on: October 7, 2016
Made with: HTML & CSS
Tags: 404 SVG animated page concept
#3: Oops! 404 error page template
Oops 404 error page design, which was developed by Israa Adnan. Moreover, you can customize it according to your wish and need.
Author: Israa Adnan
Created on: June 30, 2021
Made with: HTML & CSS
Tags: Oops 404 error page template
#4: Simple 404 page error template
Simple 404 page error template, which was developed by Naved khan. Moreover, you can customize it according to your wish and need.
Author: Naved khan
Created on: June 18, 2018
Made with: HTML & CSS
Tags: Simple 404 page error template
#5: Yeti 404 Page
Yeti 404 Page, which was developed by Darin. Moreover, you can customize it according to your wish and need.
Author: Darin
Created on: August 17, 2018
Made with: HTML, CSS(SCSS) & JS
Tags: Yeti 404 Page
#6: 404 Page UI
404 Page UI, which was developed by Rafaela Lucas. Moreover, you can customize it according to your wish and need.
Author: Rafaela Lucas
Created on: November 27, 2019
Made with: HTML, CSS(SCSS) & JS
Tags: daily ui 404 Page
#7: Fargo 404 page template
Fargo 404 page design, which was developed by Nate Watson. Moreover, you can customize it according to your wish and need.
Author: Nate Watson
Created on: November 18, 2015
Made with: HTML(Pug), CSS(SCSS) & JS
Tags: Fargo 404 page design
#8: GSAP 404 typed message using SplitText
GSAP 404 typed message using SplitText, which was developed by Selcuk Cura. Moreover, you can customize it according to your wish and need.
Author: Selcuk Cura
Created on: October 22, 2017
Made with: HTML, CSS(SCSS) & JS
Tags: GSAP 404 typed message using SplitText
#9: Mars 404 Error Page
Mars 404 Error Page, which was developed by Asyraf Hussin. Moreover, you can customize it according to your wish and need.
Author: Asyraf Hussin
Created on: September 2, 2018
Made with: HTML & CSS
Tags: Mars 404 Error Page
#10: 404 Error Page Template Example
404 Error Page Design, which was developed by Ricardo Prieto. Moreover, you can customize it according to your wish and need.
Author: Ricardo Prieto
Created on: November 4, 2017
Made with: HTML & CSS
Tags: 404 Error Page Design
#11: CSS 404 page template
CSS 404 page template, which was developed by agathaco. Moreover, you can customize it according to your wish and need.
Author: agathaco
Created on: July 28, 2018
Made with: HTML(Pug) & CSS(SCSS)
Tags: CSS 404 page
#12: Error 404 Page not found
Error 404 Page not found, which was developed by Robin Selmer. Moreover, you can customize it according to your wish and need.
Author: Robin Selmer
Created on: August 22, 2017
Made with: HTML & CSS(SCSS)
Tags: Error 404 Page not found
#13: Neon – 404 html template
Neon – 404 html template, which was developed by Tibix. Moreover, you can customize it according to your wish and need.
Author: Tibix
Created on: August 27, 2019
Made with: HTML & CSS(SCSS)
Tags: Neon 404 html template
#14: Sassy page not found template
Sassy page not found template, which was developed by Justin Juno. Moreover, you can customize it according to your wish and need.
Author: Justin Juno
Created on: May 7, 2020
Made with: HTML & CSS(SCSS)
Tags: page not found template
#15: Animated 404 page design html
Animated 404 page design html, which was developed by Jaymie Rosen. Moreover, you can customize it according to your wish and need.
Author: Jaymie Rosen
Created on: October 15, 2017
Made with: HTML, CSS & JS
Tags: Animated 404 page design html
#16: Pure CSS Error Page 404 vampire
Pure CSS Error Page 404 vampire, which was developed by Omar Dsooky. Moreover, you can customize it according to your wish and need.
Author: Omar Dsooky
Created on: August 10, 2017
Made with: HTML & CSS
Tags: Pure CSS Error Page 404 vampire
#17: Simple 404 Error page
Simple 404 Error page, which was developed by vineeth.tr. Moreover, you can customize it according to your wish and need.
Author: vineeth.tr
Created on: April 12, 2016
Made with: HTML & CSS(SCSS)
Tags: Simple 404 Error page
#18: HTML CSS 404 Crying Baby Page Template
HTML CSS 404 Crying Baby Page Template, which was developed by vineeth.tr. Moreover, you can customize it according to your wish and need.
Author: vineeth.tr
Created on: October 12, 2016
Made with: HTML(Pug) & CSS(SCSS)
Tags: HTML CSS 404 Crying Baby Page Template
#19: CSS Train 404 Page
CSS Train 404 Page, which was developed by Carla. Moreover, you can customize it according to your wish and need.
Author: Carla
Created on: November 3, 2018
Made with: HTML & CSS
Tags: CSS Train 404 Page
#20: Pure CSS Animated 404 error page template
Pure CSS Animated 404 error page template, which was developed by Sergio. Moreover, you can customize it according to your wish and need.
Author: Sergio
Created on: March 27, 2018
Made with: HTML & CSS(SCSS)
Tags: Pure CSS Animated 404 error page template
#21: SVG 404 page not found template
SVG 404 page not found template, which was developed by Sylvain Lepinard. Moreover, you can customize it according to your wish and need.
Author: Sylvain Lepinard
Created on: August 9, 2019
Made with: HTML & CSS(SCSS)
Tags: SVG 404 page not found template
#22: Fully responsive 404 page
Fully responsive 404 page, which was developed by Kasper De Bruyne. Moreover, you can customize it according to your wish and need.
Author: Kasper De Bruyne
Created on: February 18, 2020
Made with: HTML, CSS(SCSS) & JS
Tags: Fully responsive 404 page
#23: Responsive custom 404 page
Responsive custom 404 page, which was developed by Ash. Moreover, you can customize it according to your wish and need.
Author: Ash
Created on: September 28, 2017
Made with: HTML & CSS
Tags: Responsive custom 404 page
#24: Wild West 404 Error page Concept
Wild West 404 Error page Concept, which was developed by Zissis Vassos. Moreover, you can customize it according to your wish and need.
Author: Zissis Vassos
Created on: August 26, 2019
Made with: HTML & CSS
Tags: Wild West 404 Error page Concept
#25: html template 404
html template 404, which was developed by Jhey. Moreover, you can customize it according to your wish and need.
Author: Jhey
Created on: March 23, 2020
Made with: HTML(Pug), CSS & JS
Tags: html template 404
#26: Windows 10 style 404 error design
Windows 10 style 404 error design, which was developed by Marco Peretto. Moreover, you can customize it according to your wish and need.
Author: Marco Peretto
Created on: February 8, 2019
Made with: HTML & CSS
Tags: 404 error design
#27: 404 Error Page: Animated SVG GSAP
404 Error: Animated SVG GSAP, which was developed by christine i. Moreover, you can customize it according to your wish and need.
Author: christine i
Created on: February 22, 2020
Made with: HTML, CSS & js
Tags: 404 Error
#28: Custom 404 error page design
Custom 404 error page design, which was developed by Muhammad Rauf. Moreover, you can customize it according to your wish and need.
Author: Muhammad Rauf
Created on: December 3, 2021
Made with: HTML & CSS
Tags: Custom 404 error page design
#29: Oops! page not found template
Oops! page not found template, which was developed by Swarup Kumar Kuila. Moreover, you can customize it according to your wish and need.
Author: Swarup Kumar Kuila
Created on: August 14, 2020
Made with: HTML & CSS
Tags: page not found template
#30: Awesome 404 page not found
Awesome 404 page not found, which was developed by gavra. Moreover, you can customize it according to your wish and need.
Author: gavra
Created on: April 19, 2014
Made with: HTML, CSS & JS
Tags: Awesome 404 page not found
#31: Error 404: Monument Valley inspiration
Error 404: Monument Valley inspiration, which was developed by Sussie Casasola. Moreover, you can customize it according to your wish and need.
Author: Sussie Casasola
Created on: April 29, 2018
Made with: HTML(Pug) & CSS(Sass)
Tags: Error 404
#32: 404 page
404 page, which was developed by Julia. Moreover, you can customize it according to your wish and need.
Author: Julia
Created on: September 7, 2018
Made with: HTML & CSS(Sass)
Tags: 404 page
#33: 404 SVG Error Based Page
404 SVG Error Based Page, which was developed by Dave Pratt. Moreover, you can customize it according to your wish and need.
Author: Dave Pratt
Created on: September 6, 2017
Made with: HTML & CSS(SCSS)
Tags: 404 SVG Error Based Page
#34: bootstrap 404 error page template
bootstrap 404 error page template, which was developed by Aji. Moreover, you can customize it according to your wish and need.
Author: Aji
Created on: June 26, 2021
Made with: HTML & CSS
Tags: bootstrap 404 error page template
#35: Cool 404 error page
Cool 404 error page, which was developed by Anton Lukin. Moreover, you can customize it according to your wish and need.
Author: Anton Lukin
Created on: November 1, 2018
Made with: HTML & CSS
Tags: Cool 404 error page
#36: 404 error template
404 error template, which was developed by Natalia. Moreover, you can customize it according to your wish and need.
Author: Natalia
Created on: January 4, 2021
Made with: HTML & CSS
Tags: 404 error template
Our Awesome Tools
#01: Lenny Face
#02: Fancy Text Generator
A 404 error means “not found”. This is usually the page you get when you make a mistake spelling page name in a site, or if the page is deleted or moved. The problem is that the standard 404 page is ugly and unhelpful. So here are 24 excellent 404 error page html templates that can be used for common server error 404.
404 Idea Style
Beautiful 404 Error Page inspired by Idea Template. Site links included for better user experience.
Download 404 Idea Style →
Lost in the Clouds
Simple and aesthetic template with animated background.
Download Lost in the Clouds – Error 404 →
Sleek Server Error Pages
This is a clean, web 2.0 design for website / server error pages. It is flexible and very easy to customize. It comes with 5 of the most common error pages (404, 403, 401, 500 and 503) but it’s very easy to add more if needed. All text is real text so adding more pages is a breeze, no image editing required. Easy setup and configure PHP version now included (configuration not necessary unless you want to customize it further).
Download Sleek Server Error Pages →
Error Template
Fun and stylish animated error page template that you can use with unlimited error codes (404, 403, etc). Be unique with this cute octopus in your error pages. This template is made with HTML 5 and CSS 3 .
Download Error Template →
Lost in Space
Ready for all common HTTP errors, like 401, 403, 404, 500 and 503 or for many other purposes.
Download Lost in Space – Error 404 →
404 Pingu
A 404 error page template showing a browser illustration. Suitable for every website. Give it a try!
Download 404 Pingu →
PHP/Ajax error template
This is a very useful and adaptable error template which features jQuery animation and effects as well as an Ajax Error Report form in PHP .
Download Powerful Errors – PHP/Ajax error template →
Oops…404 page template
This is a nice, clean modern and solid template for your 404 page. It is designed to go straight to the point. It also has a place for navigation, so that user doesn’t have to click the back button.
Download Oops…404 page template →
Modern Error Page Template 25 in 1
These template pages can be user for any HTTP errors on your website. It comes in 5 color variations (purple, blue, red, green and orange) and 5 error codes (401, 403, 404, 500 and 503).
Download Modern Error Page Template 25 in 1 →
Stunning 404/500/etc Error Pages
High quality, extremely flexible professional error pages for a wide range of applications. Make sure you don’t lose visitors – provide useful, helpful, informative error pages to keep them at your website!High quality, extremely adaptable professional under construction/coming soon/maintenance/holding page for a wide range of applications.
Download Stunning 404/500/etc Error Pages – search/7 themes →
Creative 404 Error Page
Error pages are often overlooked by many designers. No more ugly 404/503/500 pages! Produce the wow effect.Creative 404 Error Page comes with 3 color schemes.
Download Creative 404 Error Page →
Save me – 404 Error Page
“Save me” is an unique new error page, that focuses on helping the user through the frustration of getting a website error, in an user friendly and intuitive way.
Download Save me – 404 Error Page →
Custom 404 Error Page – Missing Jigsaw Piece
Missing jigsaw piece custom 404 error page, in two styles; grey and dark gloss. The layout has subtle embossed text effects and textures, giving you an original look to the design.
Download Custom 404 Error Page – Missing Jigsaw Piece →
Fancy Jquery 404 Error Popup
This is a JQUERY script that is simple, unobtrusive, no need extra markup and is used to display 404 error in fancy popup box on the current page instead of redirecting to 404 page.Javascript in the live preview is obfuscated and comments are removed.
Download Fancy Jquery 404 Error Popup →
ak – 404 error pages
ak 404 error pages – 8 in 1These template pages can use for 404 errors on your web site. It comes by 8 different themes.
Download ak – 404 error pages →
InFamous – Modern 404 Error Page
“InFamous” is a simple but yet powerful & beautiful Error website template which helps visitors of your website not to close the browser but rather to stay on your website in a friendly and beautiful way.“InFamous” comes in a bright and a dark variant.
Download InFamous – Modern 404 Error Page →
Modern Custom 404 Error Page
You can use this Modern Custom 404 Error Page pack for any type of errors on your site. It is designed with usability in mind – to help the user get what he wants . It also has an area in footer for navigation, so user can decide where he wants to continue his browsing.
Download Modern Custom 404 Error Page →
Torned Out – 404 Template
Tore out – 404 Template Tested in Safari, Firefox, Chrome, Camino, IE6.
Download Torned Out – 404 Template →
Green Board 404 Error – Page Not Found
Here is a simple, nice way of representing 404 error page. It is designed in the form of a blackboard with 404 written in a scratchy way and has clean fonts being used to write the rest of the content.
Download Green Board 404 Error – Page Not Found →
Cthulhu – Ominous 404 Page Template
Introducing Cthulhu – HTML5 +CSS3 powered animated 404 Page Template. It uses the power of hardware accelerated CSS3 animation to produce the smooth animation of Cthulhu in newest browsers:Yes, it works on mobile devices! In older browsers it falls back to the JavaScript nicely and works just fine even in IE7 !Thus you are getting the original, unique and spooky 404 Page Template.
Download Cthulhu – Ominous 404 Page Template →
Smart 404 Page
A Simple 404 Error Page in 6 Different Color Variations with there respective psd’s.
Download Smart 404 Page →
Catch the Fish – 404 Error Page
Catch the fish 404 error page. Clean and beautiful template for every kind of project. And with magic animation.
Download Catch the Fish – 404 Error Page →
Cosmo Error Page
Cosmo Error page. It has all you need – links to your other pages, links to your social profiles, working contact form.Used resources:
Download Cosmo Error Page →
SunSet Error Pages (401, 403, 404, 500, 503)
This bundle includes the five most common server error pages: 401, 403, 404, 500, and 503. It is easy and quick to customize.
Download SunSet Error Pages →
If you call up a page that does not (no longer) exist, you are redirected to 404 pages. But that’s not bad, because 404 pages can work wonders with a little creativity, so that visitors don’t leave your site.
404 pages (or Error Page) are so called because servers return the HTTP status code 404 in case of a non-existent or no longer existing page to show that the requested page does not (no longer) exist.
A creative way with funny animations, designs and fun images often a good way to keep visitors on the go – that is, to make them not leave your website. In this course it is also important to give users the possibility to go directly to another subpage on your website (be sure to check out my 404 page). Also responsive pages have to look good, of course.
The pens can be used as a template template or as examples for your own site, let yourself be inspired! And let’s be honest…404 jokes are the best! ?
The shown pens are licensed with MIT. You can find more information about your own use in the Codepen Blog.
#1 Responsive 404 Stranger things
Author: ARiyou Jahan;
Coded in: HTML, CSS (SCSS);
#2 No Vacancy 404
Author: Riley Shaw;
Coded in: Slim, Sass, CoffeScript;
#3 404 Kittens
Author: nclud team;
Coded in: HTML, CSS (SCSS), JS;
#4 – Glitched out
Author: ZonFire99;
Coded in: HTML, CSS, JS;
#5 Fargo 404
Author: Nathaniel Watson;
Coded in: Pug, CSS (SCSS), JS;
#6 404 No signal
Author: Adem ilter;
Coded in: HTML, CSS, JS;
#7 Glitchy 404 Page
Author: Kay Pooma;
Coded in: HTML, CSS;
#8 Bluescreen – 404 Page
Author: Angela Galliat;
Coded in: HTML, CSS;
#9 404 Space
Author: Keith;
Coded in: HTML, CSS (SCSS), JS;
#10 Error page – #Project 4
Author: Jake;
Coded in: HTML, CSS (SCSS), JS;
#11 404
Author: Metty;
Coded in: HTML, CSS, JS;
#12 Space 404
Author: Ethan;
Coded in: HTML, CSS (SCSS), JS;
#13 404 Error Page
Author: anhat.dev;
Coded in: HTML, CSS, JS;
#14 Daily UI #008 – 404 Page
Author: Rafaela Lucas;
Coded in: HTML, CSS (SCSS), JS;
#15 Lost in Space (ERRORS) (not responsive)
Author: Radu;
Coded in: HTML, CSS (SCSS);
#16 404 Page Not Found
Author: João Sousa;
Coded in: HTML, PostCSS;
#17 404 Error Page
Author: miranda;
Coded in: HTML, CSS;
#18 404 Error page
Author: Abolfazl Arab;
Coded in: HTML, CSS;
#19 404 Makes bear sad ??
Author: Jhey;
Coded in: Pug, Stylus, Babel;
#20 404-magnifying-glass-svg-animation-css
Author: Maelle Gomez;
Coded in: HTML, CSS;
#21 en 404 page
Author: Arman Azizpour;
Coded in: HTML, CSS;
#22 404 Venn Diagram
Author: Michael Richins;
Coded in: HTML, CSS (SCSS);
#23 Tractor Pull 404 Error
Author: Nick Soltis;
Coded in: HTML, CSS (SCSS);
#24 Neon – 404 Page Not Found
Author: Tibix;
Coded in: HTML, CSS;
#25 8-bit mario 404
Author: JFabre;
Coded in: HTML, CSS (SCSS), Babel;
Conclusion
As you can see, there are no limits to your creativity. Which one do you like best, or have you perhaps become creative yourself? Please let me know! And maybe your 404 page will appear here soon. 🙂
Not enough? Then this could be something for you!
- Cool CSS Buttons
- CSS Navigation Menus
- CSS Hamburger Menus
- Satisfying CSS Animations
- Inspiring loading animations
Note: All pens are published on codepen.io and not by me.
Version
Error Handling
- Introduction
- Configuration
-
The Exception Handler
- Reporting Exceptions
- Exception Log Levels
- Ignoring Exceptions By Type
- Rendering Exceptions
- Reportable & Renderable Exceptions
-
HTTP Exceptions
- Custom HTTP Error Pages
Introduction
When you start a new Laravel project, error and exception handling is already configured for you. The AppExceptionsHandler
class is where all exceptions thrown by your application are logged and then rendered to the user. We’ll dive deeper into this class throughout this documentation.
Configuration
The debug
option in your config/app.php
configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG
environment variable, which is stored in your .env
file.
During local development, you should set the APP_DEBUG
environment variable to true
. In your production environment, this value should always be false
. If the value is set to true
in production, you risk exposing sensitive configuration values to your application’s end users.
The Exception Handler
Reporting Exceptions
All exceptions are handled by the AppExceptionsHandler
class. This class contains a register
method where you may register custom exception reporting and rendering callbacks. We’ll examine each of these concepts in detail. Exception reporting is used to log exceptions or send them to an external service like Flare, Bugsnag or Sentry. By default, exceptions will be logged based on your logging configuration. However, you are free to log exceptions however you wish.
For example, if you need to report different types of exceptions in different ways, you may use the reportable
method to register a closure that should be executed when an exception of a given type needs to be reported. Laravel will deduce what type of exception the closure reports by examining the type-hint of the closure:
use AppExceptionsInvalidOrderException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (InvalidOrderException $e) {
//
});
}
When you register a custom exception reporting callback using the reportable
method, Laravel will still log the exception using the default logging configuration for the application. If you wish to stop the propagation of the exception to the default logging stack, you may use the stop
method when defining your reporting callback or return false
from the callback:
$this->reportable(function (InvalidOrderException $e) {
//
})->stop();
$this->reportable(function (InvalidOrderException $e) {
return false;
});
Note
To customize the exception reporting for a given exception, you may also utilize reportable exceptions.
Global Log Context
If available, Laravel automatically adds the current user’s ID to every exception’s log message as contextual data. You may define your own global contextual data by overriding the context
method of your application’s AppExceptionsHandler
class. This information will be included in every exception’s log message written by your application:
/**
* Get the default context variables for logging.
*
* @return array
*/
protected function context()
{
return array_merge(parent::context(), [
'foo' => 'bar',
]);
}
Exception Log Context
While adding context to every log message can be useful, sometimes a particular exception may have unique context that you would like to include in your logs. By defining a context
method on one of your application’s custom exceptions, you may specify any data relevant to that exception that should be added to the exception’s log entry:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
// ...
/**
* Get the exception's context information.
*
* @return array
*/
public function context()
{
return ['order_id' => $this->orderId];
}
}
The report
Helper
Sometimes you may need to report an exception but continue handling the current request. The report
helper function allows you to quickly report an exception via the exception handler without rendering an error page to the user:
public function isValid($value)
{
try {
// Validate the value...
} catch (Throwable $e) {
report($e);
return false;
}
}
Exception Log Levels
When messages are written to your application’s logs, the messages are written at a specified log level, which indicates the severity or importance of the message being logged.
As noted above, even when you register a custom exception reporting callback using the reportable
method, Laravel will still log the exception using the default logging configuration for the application; however, since the log level can sometimes influence the channels on which a message is logged, you may wish to configure the log level that certain exceptions are logged at.
To accomplish this, you may define an array of exception types and their associated log levels within the $levels
property of your application’s exception handler:
use PDOException;
use PsrLogLogLevel;
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<Throwable>, PsrLogLogLevel::*>
*/
protected $levels = [
PDOException::class => LogLevel::CRITICAL,
];
Ignoring Exceptions By Type
When building your application, there will be some types of exceptions you simply want to ignore and never report. Your application’s exception handler contains a $dontReport
property which is initialized to an empty array. Any classes that you add to this property will never be reported; however, they may still have custom rendering logic:
use AppExceptionsInvalidOrderException;
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<Throwable>>
*/
protected $dontReport = [
InvalidOrderException::class,
];
Note
Behind the scenes, Laravel already ignores some types of errors for you, such as exceptions resulting from 404 HTTP «not found» errors or 419 HTTP responses generated by invalid CSRF tokens.
Rendering Exceptions
By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering closure for exceptions of a given type. You may accomplish this via the renderable
method of your exception handler.
The closure passed to the renderable
method should return an instance of IlluminateHttpResponse
, which may be generated via the response
helper. Laravel will deduce what type of exception the closure renders by examining the type-hint of the closure:
use AppExceptionsInvalidOrderException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (InvalidOrderException $e, $request) {
return response()->view('errors.invalid-order', [], 500);
});
}
You may also use the renderable
method to override the rendering behavior for built-in Laravel or Symfony exceptions such as NotFoundHttpException
. If the closure given to the renderable
method does not return a value, Laravel’s default exception rendering will be utilized:
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
}
Reportable & Renderable Exceptions
Instead of type-checking exceptions in the exception handler’s register
method, you may define report
and render
methods directly on your custom exceptions. When these methods exist, they will be automatically called by the framework:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
//
}
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
return response(/* ... */);
}
}
If your exception extends an exception that is already renderable, such as a built-in Laravel or Symfony exception, you may return false
from the exception’s render
method to render the exception’s default HTTP response:
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
// Determine if the exception needs custom rendering...
return false;
}
If your exception contains custom reporting logic that is only necessary when certain conditions are met, you may need to instruct Laravel to sometimes report the exception using the default exception handling configuration. To accomplish this, you may return false
from the exception’s report
method:
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
// Determine if the exception needs custom reporting...
return false;
}
Note
You may type-hint any required dependencies of thereport
method and they will automatically be injected into the method by Laravel’s service container.
HTTP Exceptions
Some exceptions describe HTTP error codes from the server. For example, this may be a «page not found» error (404), an «unauthorized error» (401) or even a developer generated 500 error. In order to generate such a response from anywhere in your application, you may use the abort
helper:
abort(404);
Custom HTTP Error Pages
Laravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a resources/views/errors/404.blade.php
view template. This view will be rendered on all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to. The SymfonyComponentHttpKernelExceptionHttpException
instance raised by the abort
function will be passed to the view as an $exception
variable:
<h2>{{ $exception->getMessage() }}</h2>
You may publish Laravel’s default error page templates using the vendor:publish
Artisan command. Once the templates have been published, you may customize them to your liking:
php artisan vendor:publish --tag=laravel-errors
Fallback HTTP Error Pages
You may also define a «fallback» error page for a given series of HTTP status codes. This page will be rendered if there is not a corresponding page for the specific HTTP status code that occurred. To accomplish this, define a 4xx.blade.php
template and a 5xx.blade.php
template in your application’s resources/views/errors
directory.
Website error pages are perhaps one of the most overlooked pieces of a fully rounded website. Not only are they important but they give you the opportunity to have a little fun. Although many web developers rely on server logs to keep an eye out for hits on error pages, I’m going to take a different approach by using a PHP generated email. In addition, we will spice up the design a bit, add basic navigation and link to the website sitemap.
About Error Pages
The most common error page — the one in which you are most likely to be familiar with — is the «404 Not Found page». More people encounter this type of error page than any other. Other common error messages you may have come across are 500 Internal Server Error, 400 Bad Request or 403 Forbidden. Wondering what the number is for? It simply refers to the HTTP code.
Default error pages are quite boring (as you can see above) and offer no purpose to visitors other than letting them know some boring error happened. For these reasons, it is a great idea to provide custom pages for the most common errors encountered. This tutorial will only cover two: the «404 Not Found» and «403 Forbidden».
Check for custom error page support
First, check to make sure your hosting provider allows you to use your own error pages. Almost all of them do, and most of them even provide a configuration area within your control panel to help you quickly create the pages. In this tutorial we will configure an Apache web server (the most common). This is easier than you might think.
Configure .htaccess
Next, connect to your server via FTP or control panel and navigate to the document root directory (usually www or public_html) which contains your website files. We will be looking for the .htaccess file. It is sometimes hidden so make sure you are viewing all files including hidden ones. If your server doesn’t have one, you can create one using any text editor. Make sure to make a backup of the .htaccess file if your server already has one.
Add the following lines to your .htaccess file:
1 |
ErrorDocument 404 /error/404.php |
2 |
ErrorDocument 403 /error/403.php |
The first half (ErrorDocument 404) is telling the server we are going to define the location of the 404 error document. The second half defines the actual location of the error document. In this case we will put it in the «error» directory and call them 404.php and 403.php, respectively.
Now save the .htaccess file and upload it to the document root directory.
Design the Custom Error Pages
It is best to stay with the same design as your website already uses so that you don’t confuse your visitors and risk losing them. You should also include helpful elements such as a polite error message, suggested links, a search feature, or a link to your sitemap. These features will depend on the level of content your website provides and what you feel will be most helpful.
As you can see below, the 404 Not Found page for Nettuts+ has stated the error and emphasized the search feature by including it in the body beneath the error message. You could take this a step further by including a short list of links to possible pages which might encourage the visitor to continue exploring more of the site (keep it simple and short though) -or even a humorous image (every one likes laughing right?). For small websites it may be a good idea to include a visible sitemap as well.
Here is something I put together for this tutorial that you can use for your website as well (included in the download above). It’s very simple so you will be able to put the content of it directly into your existing website template. As you can see, I attempted to include a little bit of a humorous element while also stating the error politely and including some options to help the visitor either find what they were looking for or continue browsing the website.
You’ll notice it does not specify the HTTP error code in the body of the page. Instead I chose to only use the error code in the title of the page. The reason for this is to keep things as simple and user friendly as possible. Most people don’t care what 404 or 403 means, they want to know what’s going on in plain English. For people who want the error code, it is still available via the title.
If you want to see some really great 404 designs visit:
- http://www.smashingmagazine.com/2009/01/29/404-error-pages-reloaded-2/
- http://www.smashingmagazine.com/2007/08/17/404-error-pages-reloaded/
- http://www.smashingmagazine.com/2007/07/25/wanted-your-404-error-pages/
- http://blogof.francescomugnai.com/2008/08/the-100-most-funny-and-unusual-404-error-pages/
The Auto-Mailer PHP and Why We Will Use Email Notification
This is the part of the tutorial in which some web guru’s might argue with. You can use your web server’s logs to check for error pages and much, much more. Why do I choose email notifications?
- I don’t want to log into my server every day and dig through all that extra information.
- I am available by email almost literally all day, the fastest way to reach me is email (or twitter). With this in mind, I want to know about 404 and 403 errors fairly quick so email is best.
- An increasing number of people are starting websites, while most of those people know almost nothing about web hosting let alone server logs. These people will only be running small sites; so email is ideal.
- Being notified right away allows me to quickly take action if a website of mine is being «harvested» (ThemeForest templates), if someone is attempting to access something restricted repeatedly or if I have a broken link somewhere.
So with all that said, let’s get on with the code shall we!
The Code
First, we will create a file named error-mailer.php which will be used to collect information about our visitor and send the email. Once you have created the file we will start by specifying our email and email settings.
1 |
<?php
|
2 |
|
3 |
# The email address to send to
|
4 |
$to_email = 'YOUR-EMAIL@DOMAIN.com'; |
5 |
|
6 |
# The subject of the email, currently set as 404 Not Found Error or 403 Forbidden Error
|
7 |
$email_subject = $error_code.' Error'; |
8 |
|
9 |
# The email address you want the error to appear from
|
10 |
$from_email = 'FROM-EMAIL@DOMAIN.COM'; |
11 |
|
12 |
# Who or where you want the error to appear from
|
13 |
$from_name = 'YourDomainName.com'; |
Then we will collect information about our visitor such as IP address, requested URI, User Agent, etc. The following code will collect that information.
1 |
# Gather visitor information
|
2 |
$ip = getenv ("REMOTE_ADDR"); // IP Address |
3 |
$server_name = getenv ("SERVER_NAME"); // Server Name |
4 |
$request_uri = getenv ("REQUEST_URI"); // Requested URI |
5 |
$http_ref = getenv ("HTTP_REFERER"); // HTTP Referer |
6 |
$http_agent = getenv ("HTTP_USER_AGENT"); // User Agent |
7 |
$error_date = date("D M j Y g:i:s a T"); // Error Date |
Now we will write the script to email the information to us with the details specified earlier.
1 |
# Send the email notification
|
2 |
require_once('phpMailer/class.phpmailer.php'); |
3 |
$mail = new PHPMailer(); |
4 |
|
5 |
$mail->From = $from_email; |
6 |
$mail->FromName = $from_name; |
7 |
$mail->Subject = $email_subject; |
8 |
$mail->AddAddress($to_email); |
9 |
$mail->Body = |
10 |
"There was a ".$error_code." error on the ".$server_name." domain". |
11 |
"nnDetailsn----------------------------------------------------------------------". |
12 |
"nWhen: ".$error_date. |
13 |
"n(Who) IP Address: ".$ip. |
14 |
"n(What) Tried to Access: http://".$server_name.$request_uri. |
15 |
"n(From where) HTTP Referer: ".$http_ref. |
16 |
"nnUser Agent: ".$http_agent; |
17 |
|
18 |
$mail->Send(); |
19 |
|
20 |
?>
|
We are using the phpMailer class to do this as demonstrated by Jeffrey via the ThemeForest blog to create a nice AJAX contact form. This version of the phpMailer class is for PHP 5/6 so if your server is running PHP 4 you will need to use the corresponding version by downloading it here.
404.php and 403.php Error Pages
The last thing we need to do is customize the error pages we designed earlier by sending the proper headers and set the $error_code variable by inserting the following code at the beginning of each page respectively (separated by ——-).
1 |
<?php
|
2 |
|
3 |
header("HTTP/1.0 404 Not Found"); |
4 |
$error_code = '404 Not Found'; // Specify the error code |
5 |
require_once('error-mailer.php'); // Include the error mailer script |
6 |
|
7 |
?>
|
8 |
------- |
9 |
<?php
|
10 |
|
11 |
header("HTTP/1.0 403 Forbidden"); |
12 |
$error_code = '403 Forbidden'; // Specify the error code |
13 |
require_once('error-mailer.php'); // Include the error mailer script |
14 |
|
15 |
?>
|
What we are doing here first is setting the correct HTTP header to return 404 Not Found and 403 Forbidden, respectively. When search engines accidentally land on this page we want to make sure they know what kind of page it is, instead of thinking that it’s a normal web page named 404.php or 403.php.
Then we specify the error code to be used in the mailer script and include the mailer script so it can do its work. This way if we make a change to the mailer script, we only need to edit one file instead of two or more (if you setup additional custom error pages).
Conclusion
There you have it! Your own custom error pages that are search engine friendly, and let you know via email when you’ve had a visitor as well as all the information you will need to fix any problems. A few last things to consider:
- Internet Explorer requires error pages that are at least 512 byes in size (if you use the example files you’ll be fine)
- High traffic websites have the potential to generate A LOT of emails so make sure you setup some sort of email filter for these error notifications so they don’t flood your inbox. I use Gmail so I just have a label and filter setup for these emails.
Did you find this post useful?
I’m a freelance designer and web developer, an author and reviewer at ThemeForest.net, a writer for the ThemeForest blog and occasionally net.tutsplus.com. When I actually manage to get away from the computer, I’m hiking, watching movies or spending time with my girlfriend in sunny Las Vegas. – View my web.appstorm.net posts here.
Introduction
In this blog post, we’ll be adding custom error pages for the three most common HTTP errors: 404 (Not Found), 403 (Forbidden), and 410 (Gone).
Typically when you request a web page, the application will return the HTTP response status code of 200 (OK), which indicates that the HTTP request was successfully processed by the server. If you look at some of the unit tests that have been generated in this Flask tutorial, there are a number of checks for a HTTP response status code of 200 (OK) to make sure a specific page is returned properly.
However, if you request a web page that does not exist, the HTTP response status code returned will be 404 (Not Found). This can occur if you are trying to access a web page that does not exist or if you accidentally typed in an incorrect site (for example with our application, if you type localhost:5000/log_in instead of localhost:5000/login). A similar result will occur if you attempt to access a web page that you don’t have permission to access. For example, if you are logged in as a standard ‘user’ but attempt to access the administrative page that we created in the Administrative Page for Viewing Users blog post.
Flask provides a very convenient function, abort(), that aborts a request with an HTTP error and provides a simple page displaying the error. However, there is a way to create custom error pages to handle specific HTTP error codes, which we’ll be implementing in this blog post.
Setup
Before starting to make any changes for this user action, let’s create a new feature branch:
(ffr_env) $ git checkout -b add_custom_error_pages (ffr_env) $ git branch
There are no new modules to install for this blog post.
Templates for the Custom Error Pages
The first step in creating the custom error pages is to define separate templates (in …/projects/templates) for each error code. We’ll be focusing on three of the more common error code (404, 403, and 410) so we’ll need to create templates for each error code.
Here is the template for the most common error message, 404 (Not Found), as defined in …/project/templates/404.html:
{% extends "layout.html" %} {% block content %} <h1>Page Not Found</h1> <h4>What you were looking for is just not there!</h4> <h4><a href="{{ url_for('recipes.index') }}">Kennedy Family Recipes</a></h4> {% endblock %}
This template provides a more custom feel than the typical error message that you see from most websites, as it still has the overall feel of the application with the Navigation Bar and footer still displayed via the inclusion of layout.html. Additionally, this error page provides a link back to the main page of the website to allow the user to get to a known state
The template for the 403 (Forbidden) error is very similar (as defined in …/projects/templates/403.html):
{% extends "layout.html" %} {% block content %} <h1>Forbidden</h1> <h4>You don't have the permission to access the requested resource. It is either read-protected or not readable by the server.</h4> <h4><a href="{{ url_for('recipes.index') }}">Kennedy Family Recipes</a></h4> {% endblock %}
Finally, the template for the 410 (Gone) error is defined in …/projects/templates/410.html:
{% extends "layout.html" %} {% block content %} <h1>Gone</h1> <h4>The target resource is no longer available at the origin server and that this condition is likely to be permanent.</h4> <h4><a href="{{ url_for('recipes.index') }}">Kennedy Family Recipes</a></h4> {% endblock %}
Registering the Error Handlers
We just created the custom templates for handling the 404 (Not Found), 403 (Forbidden), and 410 (Gone) error codes, but now we need to register the error handlers to properly render these templates. The best place to register the error handlers is in the top-level __init__.py file. Add the following lines to …/project/__init__.py to register the error handlers for these specific error codes:
############################ #### custom error pages #### ############################ @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(403) def page_not_found(e): return render_template('403.html'), 403 @app.errorhandler(410) def page_not_found(e): return render_template('410.html'), 410
Each of these blocks of code have a decorator (@app.errorhandler()) with a specific HTTP response status code to process. For each of the specified error codes, as the associated template is rendered and the error code is also returned as Flask does not automatically set the error code for you when using this decorator.
Let’s go ahead and try out some of these error codes… fire up the development server:
(ffr_env) $ python run.py
Try navigating to localhost:5000/hello and you should see the page associated with the 404 (Not Found) error code:
Now try logging in as a standard ‘user’ (ie. not an ‘admin’) and navigate to localhost:5000/admin_view_users. You should see the page associated with the 403 (Forbidden) error code:
Checking In Our Changes
Now that we’ve completed implementing the custom error pages, it’s time to check in the changes into the git repository:
$ git add .
$ git status
$ git commit -m “Added custom error pages for 404, 403, and 410 error codes”
$ git checkout master
$ git merge add_custom_error_pages
$ git push -u origin master
Conclusion
This blog post showed how to implement custom pages for specific HTTP response status codes. The three error codes that were included are three of the more common error codes: 404 (Not Found), 403 (Forbidden), and 410 (Gone).
While these error pages are not necessary for your application, they do provide an improved user experience as there is more than just a blank error message and there are multiple ways for a user to continue navigating within your application.
The files associated with this blog post can be found using the ‘v2.0’ tag in GitLab.