Как создать свою 404 ошибку

Как сделать 404 страницу

Постараюсь не сильно вдаваться в подробности, что такое 404-ая страница, достаточно открыть гугл и по запросу «Как сделать 404 страницу» — Вы обнаружите огромное количество сайтов с подробным описанием, что это такое. Я просто хочу поделиться с читателем своим способом создания 404-ой страницы. И вот, что у нас должно получиться в итоге.

 Как сделать 404 страницу

Почему обязательно надо делать свою 404-ую страницу?

Главная и единственная причина – это не потерять посетителя. У каждого пользователя наверняка возникала такая ситуация, когда нажимая на ссылки на каком-нибудь сайте, браузер вместо запрашиваемой страницы показывал свою дефолтную страницу ошибки. Ошибка возникает в результате неправильно введенного запроса или запрашиваемая страница, была удалена самим веб-мастером. В таком случае все посетители ведут себя одинаково – закрывают страницу и уходят с вашего сайта.

Хватит воду лить! Давай конкретику!

Создаем два файла – 404.html и .htaccess (этот файл без имени, но с расширением htaccess), который автоматически перенаправляет посетителя на 404.html, в случае возникновения ошибки. Чтобы перенаправление работало, в этот файл надо прописать одну единственную строку:


ErrorDocument 404 http://www.site.ru/404.html

Когда оба файла будут готовы, залить их на сервер в корень домена.

Мы уже создали пустой файл 404.html и теперь будем наполнять HTML кодом саму 404 страницу, активно применяя HTML5 и CSS3. Я придумал свой способ, как сделать простую и красивую 404 страницу.

Первым делом нужно подобрать большую и качественную картинку или фотографию размером не менее 1200×750 пикселей. Существует много сайтов со свободной лицензией, откуда можно скачать очень качественные фотографии. Я бесплатно скачал с популярного сайта pixabay.com это забавное изображение.

 Как сделать 404 страницу

Я хочу расположить картинку как фон на все окно браузера и в центре браузера написать – 404 страница не найдена и поставить ссылку на главную. Разберем подробнее самые важные моменты.

Эффект полупрозрачности RGBA

Выбранное изображение слишком яркое, надо его слегка затемнить, тогда текст будет более читаемый. Эффект полупрозрачного затемнения, можно получить используя RGBA, прописав в стилях блока следующую строчку кода:


background: rgba (0, 0, 0, 0.7);

Первые три буквы обозначают – красный, зеленый, синий и они равны нулю (то есть получаем черный цвет). А последняя буква «а» – представляет собой альфа-канал, отвечающий за полупрозрачность элемента. В нашем случае цифра 0.7 – говорит о 70% затемнения. Шкала от полной прозрачности до полной непрозрачности находиться между нулем и единицей (0…1).

Позиционирование элементов

Для правильной верстки моего примера 404 страницы, без понимания как работает свойство position, будет трудно. Посмотрев на конечный результат 404 страницы, нам надо понять структуру HTML документа. Здесь мы видим три слоя, наложенных друг на друга. Нижний слой <body> – сама картинка, средний в теге <div> – полупрозрачный блок затемнения и верхний <div> – текст. Наша задача задать нужное позиционирование содержимого этих слоев.

У среднего слоя будет абсолютное позиционирование, поскольку положение элемента (блок затемнения) задается относительно краев браузера с нулевыми отступами.


position: absolute;

Верхний текстовый слой позиционируем относительно элемента среднего слоя.


position: relative;

Код страницы 404

Имея этот готовый код и меняя только само изображение, можно наделать себе массу разных «ошибочных» страниц.


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Код страницы 404</title>
<style>
html { height: 100%; }
body {
  background: url(your_image.jpg) no-repeat;
  background-size: cover; /* Масштабирует картинку сохраняя пропорции */
  }
.over {
  background: rgba(0, 0, 0, 0.7); /* Цвет фона и значение прозрачности */
  position: absolute; /* Абсолютное позиционирование */
  left: 0; right: 0; top: 0; bottom: 0; /* Отступы от краев браузера */
  }
.404 {
  margin-top: 100px;
  text-align: center; /* Выравнивание текста по центру */
  font-size: 10em;
  color: #fcf9f9;
  position: relative; /* Относительное позиционирование */
  z-index: 2; /* Порядок наложения элемента по высоте */
  }
.notfound {
  text-align: center;
  color: #fff;
  font-size: 2em;
  position: relative; /* Относительное позиционирование */
  z-index: 2; /* Порядок наложения элемента по слоям в глубину */
  }
.notfound a {
  color: #fff;
  font-size: 0.8em;
  }
.notfound a:hover {
  color: yellow;
  text-decoration: none;
  }
</style>
</head>
<body>
<div class="over"></div>
<div class="404">404</div>
<div class="notfound">страница не найдена<br>
<a href="#"> перейти на главную страницу..</a>
</div>
</body>
</html>

Если Вы планируете заниматься созданием сайтов на заказ, то разобраться во всех тонкостях верстки, используя HTML5 и CSS3, Вам поможет мой видеокурс.

  • Создано 05.10.2017 01:11:33


  • Михаил Русаков

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

  1. Кнопка:

    Она выглядит вот так: Как создать свой сайт

  2. Текстовая ссылка:

    Она выглядит вот так: Как создать свой сайт

  3. BB-код ссылки для форумов (например, можете поставить её в подписи):

Languages:
English
Creating an Error 404 Page 日本語
(Add your language)

While you work hard to make sure that every link actually goes to a specific web page on your site, there is always a chance that a link clicked will slam dunk and become a famous 404 ERROR PAGE NOT FOUND.

All is not lost. If your visitors encounter an error, why not be a helpful WordPress site administrator and present them with a message more useful than «NOT FOUND».

This lesson will teach you how to edit your «error» and «page not found» messages so they are more helpful to your visitors. We’ll also show how to ensure your web server displays your helpful custom messages. Finally, we’ll go over how to create a custom error page consistent with your Theme’s style.

Contents

  • 1 An Ounce of Prevention
  • 2 Understanding Web Error Handling
  • 3 Editing an Error 404 Page
  • 4 Creating an Error 404 Page
  • 5 Tips for Error Pages
    • 5.1 Writing Friendly Messages
    • 5.2 Add Useful Links
  • 6 Testing 404 Error Messages
  • 7 Help Your Server Find the 404 Page
  • 8 Questions About Error Files

An Ounce of Prevention

Some errors are avoidable, you should regularly check and double check all your links. Also, if you are deleting a popular but out-of-date post, consider deleting the body of the post, and replacing it with a link referring visitors to the new page.

Understanding Web Error Handling

Visitors encounter errors at even the best websites. As site administrator, you may delete out-of-date posts, but another website may have a link to your inside page for that post.

When a user clicks on a link to a missing page, the web server will send the user an error message such as 404 Not Found. Unless your webmaster has already written custom error messages, the standard message will be in plain text and that leaves the users feeling a bit lost.

Most users are quite capable of hitting the back key, but then you’ve lost a visitor who may not care to waste their time hunting for the information. So as not to lose that visitor, at the very least, you’ll want your custom message to provide a link to your home page.

The friendly way to handle errors is to acknowledge the error and help them find their way. This involves creating a custom Error Page or editing the one that came with your WordPress Theme.

Editing an Error 404 Page

Every theme that is shipped with WordPress has a 404.php file, but not all Themes have their own custom 404 error template file. If they do, it will be named 404.php. WordPress will automatically use that page if a Page Not Found error occurs.

The normal 404.php page shipped with your Theme will work, but does it say what you want it to say, and does it offer the kind of help you want it to offer? If the answer is no, you will want to customize the message in the template file.

To edit your Theme’s 404 error template file, open it in your favorite text editor and edit the message text to say what you want it to say. Then save your changes and upload it to the theme directory of your WordPress install.

While you are examining and editing your 404 template file, take a look at the simple structure of the 404.php file that is shipped with Twenty Thirteen. It basically features tags that display the header, sidebar, and footer, and also an area for your message:

<?php
/**
 * The template for displaying 404 pages (Not Found)
 *
 * @package WordPress
 * @subpackage Twenty_Thirteen
 * @since Twenty Thirteen 1.0
 */

get_header(); ?>

	<div id="primary" class="content-area">
		<div id="content" class="site-content" role="main">

			<header class="page-header">
				<h1 class="page-title"><?php _e( 'Not Found', 'twentythirteen' ); ?></h1>
			</header>

			<div class="page-wrapper">
				<div class="page-content">
					<h2><?php _e( 'This is somewhat embarrassing, isn’t it?', 'twentythirteen' ); ?></h2>
					<p><?php _e( 'It looks like nothing was found at this location. Maybe try a search?', 'twentythirteen' ); ?></p>

					<?php get_search_form(); ?>
				</div><!-- .page-content -->
			</div><!-- .page-wrapper -->

		</div><!-- #content -->
	</div><!-- #primary -->

<?php get_footer(); ?>

So, to change the error message your visitor sees, revise the text within the h1 heading and within the page-content class; if necessary, add more paragraphs below that.

Creating an Error 404 Page

If your WordPress Theme does not include a template file named 404.php, you can create your own.

Because every theme is different, there is no guarantee that copying over the 404.php template file found in the Twenty Thirteen Theme will work, but it’s a good place to start. The error page you copy from the Twenty Thirteen Theme will adopt the style of the current theme because it actually calls the header and footer of the current theme. That’s less work for you, and you may only have to edit the message to suit your particular needs.

To use the 404.php template file from the WordPress Twenty Thirteen Theme:

  1. Copy the file /wp-content/themes/twentythirteen/404.php into the directory of your current theme.
  2. Then, as described in the previous section, edit the error message to present your desired error message.

If copying the default 404.php into your theme directory does not work well with your theme, you can also:

  • Change the Default Theme’s 404.php template file’s header, sidebar, footer, and other codes to match the rest of the Theme’s layout.

Or

  • Copy the index.php file of your current theme to a file called 404.php.
  • Open that file and delete all sections dealing with posts or comments, see The Loop.
  • Then, edit your 404 error message.

Tips for Error Pages

There are various improvements you can make to your 404 Error web pages so let’s look at some of your options.

Writing Friendly Messages

When an error message is displayed, you can say many things to help a visitor feel reassured they’ve only encountered a minor glitch, and you’re doing the best you can to help them find the information they want. You can say something clever like:

"Oops, I screwed up and you discovered my fatal flaw. 
Well, we're not all perfect, but we try.  Can you try this
again or maybe visit our <a 
title="Our Site" href="http://example.com/index.php">Home 
Page</a> to start fresh.  We'll do better next time."

You should also attempt to show the user what they want. Check out the AskApache Google 404 Plugin to add google search results to your 404.php

Or, say something shorter and sweeter. Almost anything you say is better than 404 Error Page Not Found. You can find more information about writing 404 Error pages on the Internet, like List Apart’s Perfect 404.

As an implementation of the Perfect 404 page, this solution will tell the user it’s not their fault and email the site admin.
Helpful 404 page

When a visitor gets a 404 error page, it can be intimidating, and unhelpful. Using WordPress, you can take the edge off a 404 and make it helpful to users, and yourself, too, by emailing whenever the user clicks a link to a non-existent page.

<p>You 
<?php
#some variables for the script to use
#if you have some reason to change these, do.  but wordpress can handle it
$adminemail = get_option('admin_email'); #the administrator email address, according to wordpress
$website = get_bloginfo('url'); #gets your blog's url from wordpress
$websitename = get_bloginfo('name'); #sets the blog's name, according to wordpress

  if (!isset($_SERVER['HTTP_REFERER'])) {
    #politely blames the user for all the problems they caused
        echo "tried going to "; #starts assembling an output paragraph
	$casemessage = "All is not lost!";
  } elseif (isset($_SERVER['HTTP_REFERER'])) {
    #this will help the user find what they want, and email me of a bad link
	echo "clicked a link to"; #now the message says You clicked a link to...
        #setup a message to be sent to me
	$failuremess = "A user tried to go to $website"
        .$_SERVER['REQUEST_URI']." and received a 404 (page not found) error. ";
	$failuremess .= "It wasn't their fault, so try fixing it.  
        They came from ".$_SERVER['HTTP_REFERER'];
	mail($adminemail, "Bad Link To ".$_SERVER['REQUEST_URI'],
        $failuremess, "From: $websitename <noreply@$website>"); #email you about problem
	$casemessage = "An administrator has been emailed 
        about this problem, too.";#set a friendly message
  }
  echo " ".$website.$_SERVER['REQUEST_URI']; ?> 
and it doesn't exist. <?php echo $casemessage; ?>  You can click back 
and try again or search for what you're looking for:
  <?php include(TEMPLATEPATH . "/searchform.php"); ?>
</p>

Add Useful Links

If you encounter a «page not found» situation on the WordPress site, it is filled with helpful links to direct you to the various categories and areas of information within the WordPress site. Check it out at http://wordpress.org/brokenlink.php.

To add similar useful links to your 404 page, create a list, or a paragraph, so the visitor can easily determine which section might be useful to visit. Information of that nature is much better than having the user just reach a dead-end. To help you understand how to link to documents within your site, especially to Pages and Categories, see Linking_Posts_Pages_and_Categories.

Testing 404 Error Messages

To test your custom 404 page and message, just type a URL address into your browser for your website that doesn’t exist. Make one up or use something like:

http://example.com/fred.php

This is sure to result in an error unless you actually have a php file called fred. If your error page doesn’t look «right», you can go back and edit it so it works correctly and matches your Theme’s look and feel.

Help Your Server Find the 404 Page

By default, if WordPress cannot find a particular page it will look for the 404.php web page. However, there may be cases where the web server encounters a problem before WordPress is aware of it. In that case, you can still guarantee that your web server sends the visitor to your 404.php template file by configuring your web server for custom 404 error handling.

To tell your web server to use your custom error files, you’ll need to edit the .htaccess file in the main directory (where main index.php file resides) of your WordPress installation. If you don’t have an .htaccess file, see Editing Rewrite Rules (.htaccess) on how to create an .htaccess file.

To ensure the server finds your 404 page, add the following line to your .htaccess file:

ErrorDocument 404 /index.php?error=404

The url /index.php is root-relative, which means that the forward slash begins with the root folder of your site. If WordPress is in a subfolder or subdirectory of your site’s root folder named ‘wordpress’, the line you add to your .htaccess file might be:

ErrorDocument 404 /wordpress/index.php?error=404

Questions About Error Files

Why not just hard code the path all the way to the 404.php file?
By allowing index.php to call the error file, you ensure that the 404.php file used will change automatically as you change your theme.
What happens if I switch to a theme that does not have a 404.php file?
Visitors clicking on a broken link will just see a copy of the home page of your WordPress site (index.php), but the URL they see will be the URL of the broken link. That can confuse them, especially since there is no acknowledgement of the error. But this is still better than a getting a «NOT FOUND» message without any links or information that could help them find what they seek.

My file .htaccess handles all requests from /word_here to my internal endpoint /page.php?name=word_here. The PHP script then checks if the requested page is in its array of pages.

If not, how can I simulate an error 404?

I tried this, but it didn’t result in my 404 page configured via ErrorDocument in the .htaccess showing up.

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

Am I right in thinking that it’s wrong to redirect to my error 404 page?

Valerio Bozz's user avatar

asked Sep 4, 2009 at 19:29

Eric's user avatar

2

The up-to-date answer (as of PHP 5.4 or newer) for generating 404 pages is to use http_response_code:

<?php
http_response_code(404);
include('my_404.php'); // provide your own HTML for the error page
die();

die() is not strictly necessary, but it makes sure that you don’t continue the normal execution.

answered Jan 11, 2017 at 14:28

blade's user avatar

bladeblade

11.8k7 gold badges36 silver badges38 bronze badges

2

What you’re doing will work, and the browser will receive a 404 code. What it won’t do is display the «not found» page that you might be expecting, e.g.:

Not Found

The requested URL /test.php was not found on this server.

That’s because the web server doesn’t send that page when PHP returns a 404 code (at least Apache doesn’t). PHP is responsible for sending all its own output. So if you want a similar page, you’ll have to send the HTML yourself, e.g.:

<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
include("notFound.php");
?>

You could configure Apache to use the same page for its own 404 messages, by putting this in httpd.conf:

ErrorDocument 404 /notFound.php

Kzqai's user avatar

Kzqai

22.5k25 gold badges105 silver badges135 bronze badges

answered Sep 4, 2009 at 19:50

JW.'s user avatar

JW.JW.

50.5k36 gold badges114 silver badges142 bronze badges

3

Try this:

<?php
header("HTTP/1.0 404 Not Found");
?>

answered Sep 4, 2009 at 19:36

Ates Goral's user avatar

Ates GoralAtes Goral

137k26 gold badges137 silver badges190 bronze badges

2

Create custom error pages through .htaccess file

1. 404 — page not found

 RewriteEngine On
 ErrorDocument 404 /404.html

2. 500 — Internal Server Error

RewriteEngine On
ErrorDocument 500 /500.html

3. 403 — Forbidden

RewriteEngine On
ErrorDocument 403 /403.html

4. 400 — Bad request

RewriteEngine On
ErrorDocument 400 /400.html

5. 401 — Authorization Required

RewriteEngine On
ErrorDocument 401 /401.html

You can also redirect all error to single page. like

RewriteEngine On
ErrorDocument 404 /404.html
ErrorDocument 500 /404.html
ErrorDocument 403 /404.html
ErrorDocument 400 /404.html
ErrorDocument 401 /401.html

answered Mar 30, 2016 at 10:34

Irshad Khan's user avatar

Irshad KhanIrshad Khan

5,6302 gold badges43 silver badges39 bronze badges

1

Did you remember to die() after sending the header? The 404 header doesn’t automatically stop processing, so it may appear not to have done anything if there is further processing happening.

It’s not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your «what are you looking for?» page for the human reader.

answered Sep 4, 2009 at 19:50

Eli's user avatar

EliEli

97.1k20 gold badges76 silver badges81 bronze badges

Standard Apache 404 error looks like this:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body></html>  

Thus, you can use the following PHP code to generate 404 page that looks exactly as standard apache 404 page:

function httpNotFound()
{
    http_response_code(404);
    header('Content-type: text/html');

    // Generate standard apache 404 error page
    echo <<<HTML
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body></html>  
HTML;

    exit;
}

answered Mar 20 at 16:14

Dima L.'s user avatar

Dima L.Dima L.

3,39332 silver badges30 bronze badges

try putting

ErrorDocument 404 /(root directory)/(error file) 

in .htaccess file.

Do this for any error but substitute 404 for your error.

StackedQ's user avatar

StackedQ

3,9891 gold badge27 silver badges41 bronze badges

answered May 20, 2018 at 19:41

the red crafteryt's user avatar

In the Drupal or WordPress CMS (and likely others), if you are trying to make some custom php code appear not to exist (unless some condition is met), the following works well by making the CMS’s 404 handler take over:

<?php
  if(condition){
    do stuff;
  } else {
    include('index.php');
  }
?>

answered Jan 28, 2019 at 19:38

Mike Godin's user avatar

Mike GodinMike Godin

3,6663 gold badges27 silver badges29 bronze badges

Immediately after that line try closing the response using exit or die()

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;

or

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
die();

answered May 25, 2018 at 4:22

user5891645's user avatar

4

try this once.

$wp_query->set_404();
status_header(404);
get_template_part('404'); 

Nikos Hidalgo's user avatar

answered Mar 31, 2020 at 4:24

Mani Kandan's user avatar

1

Посетители сайта видят 404 ошибку, если страница, на которую они пытаются перейти, не существует или по какой-то причине сервер не может её найти. В статье рассмотрим, что это за ошибка и какое влияние она оказывает на поведенческие факторы пользователей и SEO. А также разберем, как настроить редирект 404 ошибки через .htaccess.

Что такое ошибка 404

Ошибка 404 (File not found) возникает, когда сервер не может найти запрашиваемую пользователем страницу. От ее появления не застрахован ни один сайт. Достаточно ввести в адресной строке после домена рандомный набор символов. Например:

http://site.ru/asdfjkl;

Сервер не сможет найти страницу, и отобразится ошибка:



редирект 404 1
Ошибка 404 на сайте reg.ru

Также с ошибкой 404 можно столкнуться в следующих случаях:

  • Администратор сайта удалил или переместил страницу, но не сделал редирект на актуальный материал.
  • Изменилась структура сайта, а у страниц остались старые URL.
  • Посетитель опечатался в адресе, когда вводил его вручную.
  • Посетитель перешел по «битой» ссылке, которая ведет на несуществующую (удаленную или перемещенную) страницу.

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

Код 404 не стоит путать с другими похожими ошибками. Например, 403-й, которая означает, что доступ к ресурсу ограничен или запрещен. Подробнее о том, как ее исправить в статье.

Иногда при загрузке несуществующей страницы браузер получает ответ 200 вместо 404. Такой случай называют Ложной ошибкой (Soft 404). Он означает, что со страницей всё в порядке, хотя пользователь видит ошибку. Также проблема заключается в том, что Яндекс и Google показывают эту страницу в результатах поиска. Чтобы проверить код ошибки, воспользуйтесь проверкой URL от Google.

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

Возможные последствия для сайта

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

Также важно следить за тем, чтобы на сайте было как можно меньше несуществующих страниц, битых ссылок и т. п. Чтобы отыскать их, можно воспользоваться веб-инструментами Яндекс и Google или другими сервисами. Найдите все, что нужно поправить, настройте 301-й редирект на актуальные материалы и замените некорректные ссылки.

Если на сайте регулярно встречается ошибка 404, это может повлиять на поведение посетителей. Пользователи, которые многократно видят сообщение о том, что страница не существует/не найдена, с большой вероятностью покинут сайт и уйдут к конкурентам.

Рекомендации по созданию страницы 404

Если сайт создавался в CMS WordPress, Joomla, Drupal и т. п., в нем, скорее всего, предусмотрена страница ошибки 404. Но она может быть неинформативной или отличаться от дизайна остальных страниц вашего веб-ресурса.

Лучше всего — создать свою страницу для ошибки 404. Если вы владеете навыками верстки и дизайна, можно сделать эту страницу красивой, шуточной и необычной. Это хорошо воспринимается пользователями и снижает негативный эффект.

Важно, чтобы страница была информативной и полезной:

  • Объясните, что случилось и почему пользователю попалась ошибка;
  • Посоветуйте, что пользователю стоит сделать, чтобы найти интересующий его контент;
  • Оставьте каналы для связи и возможность связаться с поддержкой сайта.

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

Примеры страниц с ошибкой 404



редирект 404 2
СберМаркет предлагает познать мудрость котов и цены на сайте



редирект 404 3
404 ошибка в разделе «Помощь» на сайте REG.RU

Как создать страницу ошибки 404 и настроить редирект на нее в .htaccess

  1. 1.

    Создайте страницу одним из следующих способов:

    • Если вы знаете HTML и CSS, напишите код страницы самостоятельно и загрузите файл с названием 404.html в корневую папку сайта.

    • Если навыков верстки нет, в интернете можно найти бесплатные шаблоны со страницами ошибки. Скачайте файл и добавьте его в корневую папку.

    • Если вы используете WordPress, воспользуйтесь плагином 404page — your smart custom 404 error page по инструкции ниже. Обратите внимание! Если вы воспользовались плагином, вам не нужно прописывать путь к файлу в .htaccess.


    Как настроить страницу в плагине WordPress

    1) Откройте админку вашего сайта в WordPress.

    2) Перейдите в раздел «Плагины» и нажмите Добавить новый.

    3) В строке поиска введите название 404page — your smart custom 404 error page.

    4) Нажмите УстановитьАктивировать:



    редирект 404 4

    5) Перейдите в раздел Внешний вид404 Error Page.

    6) Выберите в списке Sample Page, чтобы сменить стандартную страницу ошибки, и нажмите Edit Page:



    редирект 404 5

    7) Создайте страницу в открывшемся визуальном редакторе и нажмите Обновить:



    редирект 404 6

    Готово! После обновления страница будет использоваться автоматически.

  2. 2.

    Откройте конфигурационный файл .htaccess в корневой папке вашего сайта и добавьте в него строку:

    ErrorDocument 404 https://site.ru/404.html

    Где вместо site.ru — домен вашего сайта.

  3. 3.

    Сохраните изменения.

Готово! Теперь при возникновении 404 ошибки, в браузере пользователей будет открываться созданная вами кастомная страница.

Также рекомендуется закрыть служебную страницу 404 от индексации, чтобы она не возникала в поисковой выдаче вместе с остальными страницами сайта. Для этого откройте файл robots.txt в корневой папке сайта, добавьте соответствующую команду и сохраните изменения:

Редирект с 404 на главную (не рекомендуется)

Чтобы не создавать отдельную страницу ошибки 404, некоторые веб-разработчики прописывают в .htaccess редирект на главную страницу сайта. Это нежелательно делать с точки зрения SEO-оптимизации.

Также редирект на главную страницу может ввести пользователей в заблуждение. Представьте, что вместо искомой страницы у посетителя открывается главный экран сайта. Будет непонятно, почему это произошло, ведь пользователь искал какой-то конкретный контент и не узнает, что не сможет найти его.

Рекомендуется использовать специальные страницы для ошибки 404.

Проверка редиректа 404

Проверить, корректно ли все настроено можно в Яндекс.Вебмастер и Google Search Console.

Яндекс.Вебмастер

Если вы используете его впервые, укажите домен вашего сайта и пройдите проверку валидации, добавив файл в корневую папку сайта. Это займет несколько минут.

  1. 1.

  2. 2.

    Перейдите в раздел ИнструментыПроверка ответа сервера.

  3. 3.

    Введите название страницы ошибки и нажмите Проверить.

  4. 4.

    В коде статуса HTTP должно отображаться 404 Not Found:



    редирект 404 7

Google Search Console

Если вы используете этот инструмент впервые, укажите свой домен и пройдите валидацию, добавив TXT-запись/загрузив файл в корневую папку сайта или с помощью других способов.

  1. 1.

  2. 2.

    Перейдите в раздел «Покрытие» в меню справа. Здесь будет отображаться информация о страницах ошибок.

На сайте небольшого объема можно самостоятельно следить за наличием ошибок и постараться не допускать того, чтобы на нём было много страниц, утративших актуальность. Своевременно настраивайте 301 редиректы, когда статья в справке, страница или товар теряют актуальность.

Если сайт многораздельный и многостраничный, вручную мониторить его будет сложно. Рекомендуется использовать для поиска страниц ошибки 404 онлайн-сервисы (Serpstat, BadLincs.ru и другие). Также можно воспользоваться плагинами в CMS. Замените ссылки и настройте редиректы. А также создайте понятную красочную страницу ошибки с объяснением причины, ссылками на основные разделы и строкой поиска.

There can be many reasons a user cannot gain access to a website. One of these is known as a 404! error. Quite simply an HTML 404! error message is a Hypertext Transfer Protocol (HTTP) status code indicating the server could not find the requested website. In other words, your web browser can connect with the server, but the specific page you are trying to access cannot be reached. In this tutorial, we will build an HTML 404 error web page to customize what the visitor sees when they land there. We will use some CSS as well to further enhance the page.

Why the 404! HTML Error Appears

When an HTTP 404 appears on your screen, it means that although the server is reachable, the specific page you are looking for is not. The web page is either broken, or it no longer exists. The 404 error code can appear in any browser, regardless of the type of browser you are using.

There are several reasons why you might be getting an HTTP 404 code:

  • One typical trigger for an error 404 message is when the page has been deleted from the website.
  • The page was moved to another URL and the redirection was done incorrectly.
  • You entered an incorrect URL address.
  • Although it happens very rarely, sometimes the server malfunctions.
  • The entered domain name does not exist anymore. 

Unfortunately, broken links are often left for long periods of time after the page has been deleted or moved. Even when web owners maintain their web sites, sometimes the owner may delete the site, or change the name of the site. This means that when someone clicks on an “old” link, they will no longer be able to find that site. Unfortunately, due to many people putting up URLS to web sites all over the place, there will ultimately be links that actually link to nowhere.

It is common for owners of websites to not check their external links regularly which leads to users trying to access a dead link. Web maintenance is essential for this reason.

Create a “Page Not Found” HTML Web Page

If a visitor to your website reaches an old and non-existent web page, the server that hosts that website will show a “404” error that basically says the page can not be found. Instead of allowing the server to show a bland, default error page, you can create one of your own and get as creative as you want with it.

Let us jump into step one of our tutorial.

Step 1: Create an HTML Landing Web Page

Let us start by simply creating a basic HTML page. This will be the foundation for creating a more exciting and informative 404! Error web page for visitors to land on.

Open a text editor, save the file as “shorelinesurfteam.html” and put in the following HTML code. Save your file again when done.

<html>
<head>
<style type=text/css>


</style>

</head>

<body>


</body>

</html>

To assist those who have landed on this “non-existent” page, you can add some helpful information to guide them on the right path. Perhaps add some information as to why the page does not exist anymore. Add something like this into the HTML. Feel free to copy the following code and resave your html file.

<html>
<head>
<style type=text/css>

</style>


</head>

<body><p>This was a web page for an organization that used to exist. This organization no longer exists as it has been replaced with a new organization to teach surf kids the values and love of the ocean. The new site is: https://www.pleasurepointsurfclub.com/
<br><br> 
If you came upon this page by mistake, try checking the URL in your web browser.</p>


</body>
</html>

The following illustration identifies the text we added to make the page more informative.

HTML code image

To punch up the text font, let us add a style. Copy the following code and resave your HTML file.

!DOCTYPE html>
<html>
<head>
<style type=text/css>


p {    color: blue;    
font-weight: 900;    

font-size: 20px;    
font-family: Helvetica, Arial, sans-serif;    
}


</style>

</head>

<body>

<p>This was a web page for an organization that used to exist. This organization no longer exists as it has been replaced with a new organization to teach surf kids the values and love of the ocean. The new site is: https://www.pleasurepointsurfclub.com/
<br><br> 
If you came upon this page by mistake, try checking the URL in your web browser.</p>


</body>

</html>

Add an image and change your text color to a custom hex color if you want as well by adding the HTML to reference the image. The image can go in your root directory as well.

!DOCTYPE html>
<html>
<head>

<style type=text/css>


p {    color: #0ecc8a;    

font-weight: 900;   
font-size: 20px;    
font-family: Helvetica, Arial, sans-serif;   
 }

</style>

</head>

<body>


<a href="#"><img src="site.jpg"></a>


<p>This was a web page for an organization that used to exist. This organization no longer exists as it has been replaced with a new organization to teach surf kids the values and love of the ocean. The new site is: https://www.pleasurepointsurfclub.com/
<br><br> 
If you came upon this page by mistake, try checking the URL in your web browser.</p>


</body>

</html>

Step 2: Tell the Server to Use Your HTML 404! Error Page

Create a “.htaccess” file. This text file serves the purpose of passing on instructions to the server.

There might already be a .htaccess file in the root folder of your web hosting space. If there is, download it and amend that. It may be a hidden file. If so, you may need to adjust your server settings so that you can view this file.

In this “.htaccess” file you will need to add this line:

ErrorDocument 404 /shorelinesurfteam.html

This is all you need to add. You do not need to add any HTML code.

What this does is tell the server that when it encounters a 404 error, it should load the shorelinesurfteam.html file in the root folder.

Step 3: Save .htaccess File to the Root Directory

Save your “.htaccess” file and upload it to the root folder of your web site. When the server encounters a not-found error, your error page will be shown.

Now when a visitor finds the web page (per our code above)

Instead of seeing this:

sample error page

They will see the following more informative and friendly error page that you have created.

sample error page

To make the green text stand out more, you can add a div element with a color background as such:

<html>
<head>

<style type=text/css>
p {
    color: #0ecc8a;
    font-weight: 900;
    font-size: 20px;
    font-family: Helvetica, Arial, sans-serif;    
}

div {
  background-color: gray;
}

</style>
</head>

<body>

<a href=”#”><img src=”site.jpg”></a>

<div>
<p>This was a web page for an organization that used to exist. This organization no longer exists as it has been replaced with a new organization to teach surf kids the values and love of the ocean. The new site is: https://www.pleasurepointsurfclub.com/
<br><br> 
If you came upon this page by mistake, try checking the URL in your web browser.</p>
</div>

</body>
</html>

This will yield the following:

sample error page

Now, you can be as artistic as you like to create your fancy, informative 404.html page. Always keep the visitor to the page in mind to enhance their experience.

See the HTML Font Families to learn how to enhance your text, and also check out the CSS Background Tutorial to learn how to enhance the background of your web page. 

Where to Next?

This introduction to the 404 page error should provide a starting point for further inquiry into web page management and the unlimited creative aspects that HTML offers. In the next blogs, you will be able to explore other areas of HTML design. Continue to be inspired, explore further and dive deeper into the world of web design.

Enroll in our Intro to Programming Nanodegree program today!

Start Learning

Понравилась статья? Поделить с друзьями:
  • Как создать свой аккаунт если пишет ошибка
  • Как создать свои ошибки python
  • Как создать ошибку с моим текстом
  • Как создать ошибку при запуске файла
  • Как создать ошибку в реестре