Шаблоны 403 ошибки

Web designers have gotten used to turning errors into opportunities. It’s no secret that the common, most widely occurring (and surprisingly recognizable) HTTP status code 404, aka “Not Found,” was forced by developers to bring benefits to the project. In the past it scared away users, destroyed the overall impression and was a nightmare for developers. Everyone wanted it to disappear once and for all.

Today, it is an essential detail of a website. WordPress even has a specifically assigned template for it. The “404 page” is an integral element of user experience. In the majority of cases, it has not only a beautiful design but also a theme that is aimed to contribute to the entire aesthetic of a website.

Along with the well-thought-out design, interactions and even animations, it includes useful links and getaways that help lost users to get back on track. However, the “404” error in web design is like Hipsters in real-world: They still catch our eye with their dorky glasses, “vintage” shirts and beards but they are nothing new to us. As for the “403” error, that’s a different story. It’s not as popular as its next of kin, but still, it occurs and not once in a blue moon.

Just for background, HTTP status code 403, aka “403 Forbidden”, means that you do not have permission to access the page. Reasons can vary, starting with inappropriate folder permissions and ending with a banal requirement of login credentials. Nevertheless, the rule of thumb dictates that any error is an opportunity to effect improvements. So why not turn the dummy “403 page” into a place that will serve the same duty as the “404 page”?

Let’s consider a dozen splendid takes on this type of error. They not only serve as a source of inspiration but also a source of ready-to-use solutions.

You Shall Not Pass

“You shall not pass” – was said once by one of the most powerful white-bearded wizards in the fictional world (I hope all the fans of Dumbledore forgive me for this). The final phrase of Gandalf the Grey (note Grey, not White) perfectly fits into the context here. And Noah Rodenbeek, A van Hagen and Jhey show this in practice. Their code snippets are impregnated with a spirit and charm of “The Hobbit” novel. While the first two artists re-created Gandalf with his staff, the latter just hinted at the scene, yet quite successfully.

HODOR 403

If the motifs from fictional novels featured above are not enough for you, then you should set your eyes on this code snippet from Yasio. Surprise-surprise, he got his inspiration from George R. R. Martin’s series of fantasy novels. He has come up with a work called HODOR 403. I believe for the majority out there this solution is self-explanatory. For the rest, I recommend switching to HBO and seeing for yourself why this fictional character goes perfectly well with this type of an error.

Use of Illustration and Animation

Other solutions in our list were guided by the notion that “403” symbolizes a forbidden area so that animated and static CSS illustrations were recreated namely with this idea in mind.

Error 403 – Forbidden by Aimie depicts a classic scene from the fairy tale. The animated bats, witch’s house, bare trees and creepy typography that are featured in the hours of darkness certainly do the trick here.

403 Forbidden by Dylan and 403 Forbidden by Visual Composer have some unique medieval allure. “Close the Gates”: The projects evoke namely these associations. The first one features the classic wooden guard gate door that closes before your very eyes; the second one also goes for a guard gate topic and depicts a mechanism with cogs and chains that reveals the forbidden sign.

Arturo Wibawa’s vision of the forbidden area is presented via marvelous, highly-detailed and even partially animated CSS illustration of the famous Chinese ‘The Purple Forbidden City,’ aka Palace Museum nowadays.

It’s Watching You

403 Forbidden Page by Mariana is marked by a whimsical monster-like character that, thanks to direction-aware effect, follows your mouse cursor everywhere. It recreates a feeling of being watched all the time. It also imitates a fancy fairy guard that does not allow moving forward. The project feels fun in spite of the “menacing” look of the mascot.

Be Persistent

Gabriele Corti also offers a vision of a “403” error page. His “Persistence is a key” project depicts an entire process of initially denying access and granting it after the right user action. The right actions imply inserting a key into a keyhole Nevertheless, you can always use this concept as a base for some advanced actions like inputting login and password.

Keeping it Simple

403 by lsgrrd is an oversimplified take on a “403 Page” that certainly has a right to exist. It is minimal but straight to the point. It has a certain digital quality that oozes techno vibe inherent to the computer sphere. The blinking cursor at the end in tandem with the digital typography produces a fantastic effect. The solution is clean, elegant and straightforward.

Are You on the List?

We are going to end our collection with the project made by Cassidy Williams. Unlike the majority featured here, this solution is a metaphor from the real world that illustrates the typical situation in any popular nightclub. The bouncer is the heart and soul of this code snippet. The character was even partially animated to make everything look lifelike.

Another Opportunity to Engage Users

Truth be told, “403 Error” is not as widespread as “404 Error”, nor is it as popular and recognizable. Nevertheless, it still exists and occurs time after time. That creates a hole in a website that can break the entire user experience. So, seize the opportunity and turn it into a valid part of the project. It will undoubtedly win over some new visitors and will prevent you from losing the old ones.

Related Posts

  • 8 CSS Snippets for Creative Hyperlink Hover Effects
  • 8 CSS & JavaScript Snippets for Creating Paginated Navigations
  • 8 CSS & JavaScript Snippets for Building Mega Menus
  • 10 CSS, JavaScript & SVG Snippets for Creating Logos
  • A Long Time Ago: Code Snippets Inspired by Star Wars
  • 8 CSS & JavaScript Snippets for Creating Wild & Crazy Backgrounds
  • Code Snippets That Demonstrate the Repelling Effect in Web Design
  • 8 CSS & JavaScript Snippets for Creating Background Noise Effects
  • 8 CSS & JavaScript Snippets for Creating Unique Cursor Effects
  • 8 CSS & JavaScript Snippets for Creating Modern Blog Layouts

This page may contain affiliate links. At no extra cost to you, we may earn a commission from any purchase via the links on our site. You can read our Disclosure Policy at any time.

В зависимости от задач можно по-разному переопределить в Django стандартное поведение на реакцию ошибок, таких как 403, 404, 500 и стандартные шаблоны вывода ошибок. В официальной документации (на рус. яз. — http://djbook.ru/rel1.8/topics/http/views.html) хорошо это описывается, но тем не менее есть некоторые нюансы, о которых я хочу рассказать и показать в примерах.

В большинстве случаев можно оставить стандартное поведение Django, т. е. стандартные views (из django.views.defaults), обрабатывающие ошибки и переопределить только шаблоны.

Допустим, у нас есть шаблон ошибки 404:

# 404.html
{% extends "base.html" %}

{% block subtitle %}Страница не найдена{% endblock %}
{% block meta %}<meta name="robots" content="noindex, nofollow">{% endblock %}

{% block content %}
    <h2>Запрашиваемая страница не найдена</h2>
    <p>Возможно, неправильно указан путь в адресной строке или страница была удалена.</p>
    <p>Возврат на <a href="/">главную страницу</a></p>
{% endblock %}

А ниже описаны разные способы переопределения.

Добавление своего шаблона в templates

Самый простой способ переопределения — это добавить этот шаблон в «my_project / templates». Именно здесь django будет искать шаблон 404.html и при наличии отрендерит.

Добавление своего шаблона в другую папку

Не всегда удобно держать шаблоны ошибок в «my_project / templates» вместе с какими-то другими шаблонами и хочется их вынести в отдельную папку. Я, к примеру, использую следующую структуру папки templates в корне проекта (жирным выделены папки):

  • admin — содержит переопределяемые админские шаблонов
  • cms — содержит переопределяемые шаблоны Django CMS
  • errs — содержит шаблоны ошибок
    • 403.html
    • 404.html
    • 500.html
  • vers — содержит проверочные файлы для поисковых систем
  • base.html
  • one_col.html
  • two_col.html
  • main.html

Как видите, вынос шаблонов ошибок в отдельную папку — хорошая идея отделить их от шаблонов страниц (one_col.html, two_col.html, main.html). Чтобы указать django, где искать шаблоны по новому пути, нужно использовать метод curry, например:

# urls.py
from django.views.defaults import server_error, page_not_found, permission_denied

handler403 = curry(permission_denied, template_name='errs/403.html')
handler404 = curry(page_not_found, template_name='errs/404.html')
handler500 = curry(server_error, template_name='errs/500.html')

Замечание: в Django>=1.9 нужно добавить ещё один аргумент exception для handler403 и handler404:

handler403 = curry(permission_denied, exception=Exception('Permission Denied'), template_name='errs/403.html')
handler404 = curry(page_not_found, exception=Exception('Page not Found'), template_name='errs/404.html')

Тестирование своих шаблонов ошибок

Чтобы протестировать шаблоны ошибок, достаточно добавить соответствующие urls в urls.py, например так:

if settings.DEBUG:
    urlpatterns = [
        url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
        url(r'', include('django.contrib.staticfiles.urls')),

        # --- error pages ---
        url(r'^403$', handler403),
        url(r'^404$', handler404),
        url(r'^500$', handler500),
    ] + urlpatterns

Теперь можно переходить по адресу http://localhost:8000/404 и видеть свой кастомный шаблон ошибки. На боевом сайте нам тестовые урлы ошибок не нужны, поэтому мы добавили их в условие if settings.DEBUG:.

Создание своего представления для обработки ошибки

Если хочется изменить стандартное поведение обработки ошибок, то нужно писать своё представление. Например:

# urls.py
handler403 = 'my_app.views.show_403'
handler404 = 'my_app.views.show_404'

# my_app/views.py
# Обработка ошибки 403
from django.core.exceptions import PermissionDenied
def show_403(request):
    # какие-либо действия
    raise PermissionDenied

# Обработка ошибки 404
from django.http.response import Http404
def show_404(request):
    # какие-либо действия
    raise Http404

Можно усложнить пример с обработкой ошибки 404. Например, мы хотим отдавать разные шаблоны 404 в зависимости от того, с чего начинается отсутствующий url:

# Обработка ошибки 404
from django.http.response import Http404
def 404(request):
    if request.path.startswith('/project/'):
        return render(request, 'project_not_found.html')  # выдаст страницу, что проекта нет и, к примеру, покажет другие проекты
    if request.path.startswith('/shop/'):
        return render(request, 'product_not_found.html')  # выдаст страницу, что товара нет и, к примеру, покажет другие товары

    raise Http404  # в остальных случаях показать стандартное исключение, которое отрендерит наш шаблон 404.html

Некоторые тонкости

Проверка отдачи шаблона 404

Для проверки отдачи шаблона 404 используйте при значении переменной DEBUG=False в settings.py, иначе вам будет показан трейсбек Django.

Внимание! Если DEBUG=False, то вы должны добавить в ALLOWED_HOSTSsettings.py) допустимые доменные имена, иначе Django будет выдавать ошибку “Bad Request (400)”. На локальной машине добавляется ‘localhost’ (или 127.0.0.1).

# settings.py
ALLOWED_HOSTS = ['localhost', ]

Обратите внимание, что при DEBUG=False статические файлы не будут показываться. Для показа статических файлов нужно собрать статику и запустить сервер с опцией --insecure:

python manage.py collectstatic
python manage.py runserver --insecure

Создание своего представления для обработки 500 ошибки

При использовании стандартного представления обработки 500 ошибки в соответствующий шаблон не передаётся контекст. Сделано так для того, чтобы уменьшить количество возможных других ошибок. Поэтому шаблон должен быть простой подобный этому:

<!DOCTYPE html>
<html>
<head>
    <title>Ошибка на стороне сервера</title>
    <meta name="robots" content="noindex, nofollow">
</head>
<body>
    <p>Извините, но что-то случилось с сайтом.</p>
    <p>В техническую поддержку уже отправлено уведомление.</p>
</body>
</html>

Если будете делать своё представление для 500 ошибки, то следуйте правилам django — не передавайте RequestContext при рендеринге шаблона. Посмотрите как происходит обработка в стандартном представлении django.views.defaults.server_error.

Отображение ошибок без рендеринга шаблонов

from django.http import HttpResponseNotFound 

def test_view_1(request, param):  
  if not param:  # какое-то условие
    return HttpResponseNotFound('<p>Страница не найдена</p>')  

  return render_to_response('test_view_1.html')  


from django.http.response import HttpResponseForbidden
def test_view_2(request, param):
    if not param:
        return HttpResponseForbidden('Доступ запрещён')

    return render_to_response('test_view_2.html')

Надеюсь, статья помогла ответить на возникающие вопросы об обработке ошибок в Django.

Оцените статью

3.9 из 5 (всего 7 оценок)

После нажатия кнопки «Отправить» ваше сообщение будет доставлено мне на почту.

Артём Мальцев

Веб-разработчик, владеющий знаниями языка программирования Python, фреймворка Django, системы управления содержимым сайта Django CMS, платформы для создания интернет-магазина Django Shop и многих различных приложений, использующих эти технологии.

Права на использование материала, расположенного на этой странице https://vivazzi.pro/ru/it/django-custom-templates-for-errors/:

Разрешается копировать материал с указанием её автора и ссылки на оригинал без использования параметра rel="nofollow" в теге <a>. Использование:

Автор статьи: Артём Мальцев
Ссылка на статью: <a href="https://vivazzi.pro/ru/it/django-custom-templates-for-errors/">https://vivazzi.pro/ru/it/django-custom-templates-for-errors/</a>

Больше: Правила использования сайта

Представляю вашему вниманию книгу, написанную моим близким другом Максимом Макуриным: Секреты эффективного управления ассортиментом.

Книга предназначается для широкого круга читателей и, по мнению автора, будет полезна специалистам отдела закупок и логистики, категорийным и финансовым менеджерам, менеджерам по продажам, аналитикам, руководителям и директорам, в компетенции которых принятие решений по управлению ассортиментом.

Here we are give you 403 page design example. 403 forbidden eroor page design usign html and css. this 403 page desing usign pure css. 403 forbidden eroor is single page design. you can easily implement in your project. 403 forbidden error in php project. you can also implement in your laravel project.

We allows to free snippets of 403 forbidden html template , you can download full code of access denied page html template layout. Here in this post i will give you example of bootstrap 403 page template snippet and you will get simple code of html, css and jquery. In bootstrap custom error page snippet i give you three tab with html, css and js, you can easily get code of free error page template layout.

<!DOCTYPE html>
<html>
<head>
<link href=»https://fonts.googleapis.com/css?family=Ropa+Sans» rel=»stylesheet»>
</head>
<body>
<div class=»error-main»>
<h1>Oops!</h1>
<div class=»error-heading»>403</div>
<p>You do not have permission to access the document or program that you requested.</p>
</div>
</body>
</html>

body{
font-family: ‘Ropa Sans’, sans-serif;
margin-top: 30px;
background-color: #F0CA00;
background-color: #F3661C;
text-align: center;
color: #fff;
}
.error-heading{
margin: 50px auto;
width: 250px;
border: 5px solid #fff;
font-size: 126px;
line-height: 126px;
border-radius: 30px;
text-shadow: 6px 6px 5px #000;
}
.error-heading img{
width: 100%;
}
.error-main h1{
font-size: 72px;
margin: 0px;
color: #F3661C;
text-shadow: 0px 0px 5px #fff;
}

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

vampire free error page template

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

delete animation free error page template

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 free page template

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

unicorn free error page template

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

under maintenance free error page template

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 free error page template

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

bill free error page template

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 free error page template

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 free error page template

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 free page template

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

swinging 404 free error page template

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

torch not found free error page template

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

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

chrome 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

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

closed free error page template

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 free error page template

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 free error page template

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

404 error page caveman mode error page template

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

404 error page free error page template

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

photo free error page template

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.

Was this article helpful?

YesNo

  • WordPress Tutorials
  • February 25, 2022
  • 6 March 2022

One of our dear users sent me a question a few days ago. How to create custom 403 and 401 error pages? I concluded that there is no way to make 403 and 401 pages in WordPress unless we use other methods to build these custom pages.

To create a dedicated 404 error template in WordPress, we can create a 404.php file in our template. Then write any code we want in this file and finally make such an example for a 404 error:

Custom WordPress 404 page example
Custom WordPress 404 page example

But for error 403, this method is not responsible. Because error 403 is called from the server-side, this page’s format is also displayed from the server-side. like this:

403 error page
403 error page

However, there is always a way to do things in WordPress. Because WordPress can insert any PHP code. So let’s see how to create custom 403 and 401 pages in WordPress.

Create a Child-theme

First of all, if you have not created a child theme for your website template, start building a child theme right now. If you do not know what a child theme is, read our article about the child theme. This is why we create a child theme that if you use a WordPress template like the Ahura template, naturally, these templates will be updated, and by editing the template, your changes will be deleted.

Create Custom 403 and 401 error pages

Now we enter the template folder or the child theme. Then we create a file with the following name.

403.php

This file will save the contents of the error page 403. For example, we can write: Welcome in this file, but you do not have access here!

Of course, there is a better way. Copy the 404.php file and save it as 403.php

We do the same for error 401; we create a file with the following name in the template folder and write our desired code there.

401.php

Edit functions.php

Now we come to the part where we talk about the middle ground. Just enter the functions.php file of your website template. Then add these codes to this file. Codes must be added at the end of the Functions file before ?>

function mihanwp_custom_error_pages()
{
    global $wp_query;
 
    if(isset($_REQUEST['status']) && $_REQUEST['status'] == 403)
    {
        $wp_query->is_404 = FALSE;
        $wp_query->is_page = TRUE;
        $wp_query->is_singular = TRUE;
        $wp_query->is_single = FALSE;
        $wp_query->is_home = FALSE;
        $wp_query->is_archive = FALSE;
        $wp_query->is_category = FALSE;
        add_filter('wp_title','mihanwp_custom_error_title',65000,2);
        add_filter('body_class','mihanwp_custom_error_class');
        status_header(403);
        get_template_part('403');
        exit;
    }
 
    if(isset($_REQUEST['status']) && $_REQUEST['status'] == 401)
    {
        $wp_query->is_404 = FALSE;
        $wp_query->is_page = TRUE;
        $wp_query->is_singular = TRUE;
        $wp_query->is_single = FALSE;
        $wp_query->is_home = FALSE;
        $wp_query->is_archive = FALSE;
        $wp_query->is_category = FALSE;
        add_filter('wp_title','mihanwp_custom_error_title',65000,2);
        add_filter('body_class','mihanwp_custom_error_class');
        status_header(401);
        get_template_part('401');
        exit;
    }
}
 
function mihanwp_custom_error_title($title='',$sep='')
{
    if(isset($_REQUEST['status']) && $_REQUEST['status'] == 403)
        return "Forbidden ".$sep." ".get_bloginfo('name');
 
    if(isset($_REQUEST['status']) && $_REQUEST['status'] == 401)
        return "Unauthorized ".$sep." ".get_bloginfo('name');
}
 
function mihanwp_custom_error_class($classes)
{
    if(isset($_REQUEST['status']) && $_REQUEST['status'] == 403)
    {
        $classes[]="error403";
        return $classes;
    }
 
    if(isset($_REQUEST['status']) && $_REQUEST['status'] == 401)
    {
        $classes[]="error401";
        return $classes;
    }
}
 
add_action('wp','mihanwp_custom_error_pages');

Just as easily! Now, look at one of the pages of your website that has a 403 error.

The error will be displayed as code stored in the 403 files.

Good luck.

Понравилась статья? Поделить с друзьями:
  • Шеви нива ошибка 0123
  • Чя в3 704 10 произошла непредвиденная ошибка
  • Шеви нива ошибка 0036
  • Чукотка издавна считается традиционной житницей народов севера ошибка
  • Шеви нива коды ошибок бк штат