Ошибка 404: что значит, как исправить
В мире нет ничего идеального, в том числе и безупречных сайтов. Одним из слабых мест веб-проекта может быть страница Error 404 Not Found или просто «Страница не найдена». Этот безобидный, на первый взгляд, элемент сайта становится раздражителем для посетителей и брешью, сквозь которую уплывает желанный трафик.
Ошибка 404 означает, что пользователь перешел на страницу, где на данный момент отсутствует нужный текст и какой-либо контент. Несуществующая страница могла быть здесь раньше, возможно, ее удалили, переместили в другую категорию или подкорректировали название, в результате чего изменился URL. И здесь возникает проблема: если на нее вели внешние и внутренние ссылки, в результате переходов читатели увидят неутешительное сообщение «страница не найдена». Кто виноват и что делать?
Не стоит впадать в панику — сегодняшняя статья поможет вам просто справиться с неприятностью без потери денег и времени.
Хотите получить ценные рекомендации прямо сейчас? Тогда читайте дальше!
Что такое ошибка 404, из-за чего она возникает?
404 Not Found — стандартный код ответа веб-сервера, если он не может найти запрашиваемую страницу на сайте. Перед посещением того или иного ресурса, браузер пользователя делает запрос серверу, а тот проверяет работоспособность документа и выдает соответствующий заголовок с информацией. Когда страница исправно функционирует, приходит невидимый читателю «200 ОК», в противном случае сервер отвечает кодом 404.
Это интересно! У каждой цифры кода имеется свое значение. Первая четверка говорит о том, что запрос занял слишком много времени или юзер мог неверно ввести URL. Ноль предполагает синтаксическую неточность, а последняя четверка указывает на конкретный тип проблемы.
В идеале, пользователи не должны встречать страницы с 404 ответом сервера, однако избежать появления несуществующих документов на сайте с десятками разделов и сотнями материалов довольно проблематично. Тем более сложно отследить все коды ответа вручную — для этого лучше использовать специальные сервисы и программы (о них пойдет речь чуть позже).
Пока давайте ознакомимся с причинами возникновения error 404 not found:
- ошибка в урле или битые ссылки;
- документ был удален с ресурса;
- неправильный редирект на страницу, которая сменила адрес;
- сервер работает некорректно.
Количество несуществующих HTML-страниц растет? Необходимо действовать безотлагательно!
Как должна выглядеть идеальная страница 404 Not Found?
По умолчанию страница 404 Not Found является для читателя бесполезной. В то время как достойное оформление сгладит негативное впечатление, станет своеобразным извинением. Кроме того, грамотно настроенная страница — подсказка и ориентир для дальнейших действий.
То есть 404 обязана решать следующие задачи:
- привлекать внимание,
- объяснять пользователям ситуацию,
- подсказывать возможные варианты.
В ваших силах сделать несуществующую страницу своим преимуществом. Например, онлайн-представительству фирмы можно добавить сюда контакты и месторасположение, а интернет-магазину — поисковую строку. Некоторые вебмастера превращают Error 404 Not Found в своеобразный лендинг, размещая информацию о распродажах и специальных предложениях.
С учетом специфики ресурса предложите посетителю перейти на главную страницу, воспользоваться поиском, ознакомиться с акциями или просто развлеките его.
А знаете ли вы? Существует легенда о том, что первый веб-сервер находился именно в комнате № 404. Однако на самом деле в здании CERN, о котором идет речь, помещения с таким номером не существовало. Что это — мистика или непродуманная, вымышленная история — решайте сами!
Конвертирующая страница «ошибка 404»
На SEO-форумах многие новички задают вопрос: «Что должно быть на странице 404, чтобы она приносила ресурсу пользу?» Ответ очевиден: все, что хочет узнать читатель. Для достижения подобного эффекта пригодятся следующие элементы:
- переход на главную страницу;
- кнопка сообщения о битой ссылке;
- список популярных материалов;
- форма поиска;
- ссылка на карту сайта.
Официальные рекомендации от Google
Гугл считает, что ошибка 404 обязана вписываться в общую концепцию сайта, иметь идентичный
стиль. Этот поисковик рекомендует предоставить посетителям возможность сообщать администратору о неработающих URL. Кроме того, следует исключить индексирование «не найдено» роботами.
Как создать страницу ошибки 404?
Если страница отдает 200 Ок, а должна отдавать 404 ошибку, то исправить эту проблему можно двумя способами:
Через .htaccess
Настройка error 404 not found делается в корневом файле сайта. Создайте страницу и поместите ее в новую папку, продублировав название в .htaccess.
Пропишите в документе строку:
ErrorDocument 404 /error404.html
где /error404.html указывает путь к неработающей странице относительно корневого каталога.
В результате таких манипуляций вместо «не найдено» браузер увидит извещение о том, что страница на сервере отсутствует.
С помощью html
Метатег Refresh дает возможность автоматически обновлять или перенаправлять пользователей на другую страницу (редирект) через конкретный временной промежуток.
Для этого надо вписать следующий HTML-фрагмент:
<meta http-equiv=»Refresh» content=»5;URL=not404.htm»>
Это лучшее решение при смене адреса — ошибка 404 будет перезагружена, после чего посетитель увидит страницу с другим урлом.
Основные ошибки, связанные с реализацией страницы 404 Not Found
- Все страницы сайта имеют код ответа HTTP «200 ОК», даже те что не существуют.
- Ошибка 404 есть только в некоторых разделах.
- Слишком много страниц выдают Error 404 Not Found.
- Используется первоначальное оформление с белым фоном и стандартными словами.
- В документе нет ссылок на главную страницу или другие материалы.
- Отсутствует сообщение о том, что это неработающая страница.
- На дизайне 404 стоит 301 редирект с ответом сервера «200 ОК».
Если сервер будет отдавать неверные коды статуса, у сайта могут возникнуть проблемы с индексацией.
Как влияет ошибка 404 на пользователей и ранжирование?
Вы переходите по ссылке в предвкушении интересного и полезного контента, но вместо него видите неприветливый статусный 404 код протокола передачи данных. Чувствуя досаду, вы быстро закрываете страницу — именно так поступает, согласно опросам, большая часть пользователей (остальные либо возвращаются на предыдущую, либо посещают главную страницу).
Непродолжительное пребывание читателя на сайте или возврат в поисковую выдачу негативно сказывается на поведенческих факторах, которые в 2018 году серьезно влияют на ранжирование.
Роботы Гугла также не в восторге от большого количества страниц «не найдено». Они воспринимают это как сигнал о том, что сайт теряет в качестве и не соответствует требованиям посетителей. Следовательно, такой сайт необходимо понизить в результатах поиска.
Зачем вам потеря трафика и проседание позиций?!
Как находить и мониторить 404 ошибки?
Google Search Console
Сервис работает по тому же принципу. Если требуется проверка сайта на ошибки 404, перейдите в «Сканирование», после чего нажмите на «Ошибки сканирования», а затем на «Ошибка 404».
Специализированные сканеры
Изучить наличие ложных ссылок на несуществующие страницы можно при помощи платной программы Screaming Frog, а также бесплатных аналогом и Xenu’s Link Sleuth.
Для этого необходимо просканировать сайт вышеуказанными программами и изучить отчеты по кодам ответа сервера.
Так вы найдете не только страницы с 404 ответом сервера, но и получите список страниц где расположены некорректные ссылки.
Отслеживание через сервисы Google Analytics
Для настройки Google Analytics вставьте в error 404 not found такой код:
ga(’send’, ’pageview’, ’404.html?page=’+ document.location.pathname + document.location.search +’&from=’ + document.referrer);
(document.referrer в данном случае означает урл предыдущей страницы, а document.location.pathname + document.location.search — адрес ложной).
Узнать, сколько пользователей видели «не найдено» можно в разделе «Поведение», «Контент сайта», «Все страницы», настроив фильтр по названию отсутствующей страницы.
Виджеты в CMS
Например, на WordPress можно стандартным способом установить русифицированный плагин Broken Link Checker. После активации он выдаст битые урлы в подкатегории «Неправильные ссылки» (панель «Инструменты»). Расширение позволит редактировать, удалять ссылки и помечать их как правильные.
Как проверить, что страница действительно отдает 404 ошибку?
Через информеры
Утилита https://httpstatus.io/ позволяет за один раз изучить до 100 ссылок. Благодаря удобству и быстрой работе в списке популярных сервисов числится также Bertal.ru и MainSpy.
Проверка плагинами
Для Chrome можно бесплатно установить расширение Redirect Path.
Как избежать появления 404 ошибок?
Во-первых, при удалении большого количества страниц или товаров вместо кода 404 настройте 410 — робот сразу удалит ненужные документы, предотвратив снижение скорости загрузки сайта.
Во-вторых, при смене структуры URL и движка настройте постоянный постраничный редирект 301.
Как устранить 404 ошибки?
Пользователи попадают на 404 ошибки в основном из-за наличия «битых» ссылок на сайте. То есть чтобы избавиться от такого рода ошибок необходимо найти их источник.
Для этого потребуется краулинг специализированной программой, о которых писали выше.
Далее просто поправить код страницы, изменив битые ссылки на работающие.
В заключение
Уделите время на то, чтобы убрать ошибку 404 и сделать дизайн ложных страниц привлекательным, информативным. И посетители, и поисковые системы оценят ваши усилия по достоинству!
Команда Livepage не занимается исправлением 404 ошибки. Данный гайд можно использовать самостоятельно.