Error 404 the requested page does not exist

Если на сайте появилась ошибка 404, значит ссылка на страницу не работает. Узнайте, как исправить ошибку Error 404 Not Found и даже сделать такую страницу полезной.

Ошибка 404, либо Error 404 Not Found — ошибка, которая появляется, если браузеру не удалось обнаружить на сервере указанный URL.

Страница 404.

Сообщение об ошибке 404

Что означает ответ 404

Error 404 Not Found отображается по-разному: «HTTP 404 не найден», «Ошибка 404 Not Found», «404 Страница не найдена». Смысл надписи всегда остаётся тем же: страница отсутствует либо просто не работает. Not Found в переводе означает «не найдено».

Ошибка 404 — классический код ответа по протоколу HTTP. Он свидетельствует, что связь с сервером установлена, но данных по заданному запросу на сервере нет.

Однако если просто ввести в поисковую строку произвольный набор символов, то браузер не покажет ошибку 404 Not Found — появится сообщение, что установить соединение с конкретным сервером невозможно.

Разберёмся в техническом формировании ответа Error 404 Not Found.

Техническая сторона вопроса. При связи по HTTP браузер запрашивает указанный URL и ждёт цифрового ответа. То есть любой запрос пользователя направляется на сервер размещения искомого сайта. Когда браузеру удаётся связаться с сервером, он получает кодированный ответ. Если запрос корректный и страница найдена, отправляется ответ с кодом 200 OK, что соответствует благополучной загрузке. При отсутствии страницы отправляется ответ об ошибке.

Что значит код «404». В ответе 404 первая четвёрка указывает на то, что запрос был чрезмерно длительным или в самом адресе была ошибка. Ноль предполагает синтаксическую неточность. Завершающая цифра кода отображает конкретную причину ошибки — «4» означает отсутствие данной ссылки.

Какие ещё ошибки бывают. Ошибку 404 не нужно путать с другими ответами, которые указывают на невозможность связи с сервером. Например, ошибка 403 сообщает, что доступ к URL ограничен, а ответ «Сервер не найден» свидетельствует, что браузер не смог обнаружить место размещения сайта.

Страница 404 от Google.

Google на 404 странице сообщает о возможных причинах ошибки

Причины ошибки

Причины, по которым HTTP возвращает ответ 404 Not Found:

  • Неверный адрес. К примеру, при ручном наборе пользователь допустил опечатку в адресе либо ссылка ведёт на несуществующую страницу. При этом домен должен быть написан верно. Если пользователь ошибется в названии домена, страница вообще не загрузится (без показа ошибки).
  • Битая ссылка. Это нерабочий URL, который никуда не ведёт. Данный вариант иногда возникает при внутренней перелинковке. К примеру, раньше страница существовала, а потом её удалили и забыли убрать ссылку.
  • Удалённая страница. Когда пользователь попытается перейти на удалённую с сервера страницу, он также увидит ошибку 404. Ссылка для перехода может сохраниться в браузерных закладках или на сторонних ресурсах.
  • Неправильный редирект на страницу с изменённым адресом. Допустим, в процессе редизайна URL изменили, но оставили без внимания связанные ссылки.
  • Неполадки на сервере. Это самый редкий вариант.

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

Несуществующая страница на сайте.

Причины отсутствия страницы на сайте бывают разными

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

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

Поисковые системы относятся к Not Found более лояльно. Например, Google отмечает, что 404 страницы не влияют на рейтинг. Но если при индексации роботы будут находить все больше ошибочных страниц, вряд ли это приведёт к более высокому ранжированию.

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

Как выявить ошибку

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

Search Console Google

Консоль поиска Google позволяет находить страницы с ошибкой 404 за несколько кликов:

  1. Войдите в учётную запись Google и перейдите в Search Console.
  2. Откройте раздел «Ошибки сканирования» → «Диагностика».
  3. Кликните на «Not Found».

Чтобы получить список страниц с ошибками, подтвердите права на ресурс — добавьте проверочную запись TXT в записи DNS регистратора домена. Такая запись не повлияет на работу сайта. Подробнее о процедуре подтверждения, читайте в справке Google.

Интерфейс Search Console Google.

Для использования Search Console Google нужно подтвердить свои права на сайт

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

Сервис для вебмастеров от Яндекса поможет быстро найти все ошибки 404:

  1. Откройте Вебмастер после авторизации в Яндекс-аккаунте.
  2. Выберите «Индексирование» → «Доступные для поиска страницы» → «Исключённые страницы».
  3. В выданном списке выберите фильтр «Ошибка HTTP: 404».

Чтобы использовать Яндекс.Вебмастер, также нужно подтвердить право владения сайтом — добавить метатег в HTML-код главной страницы.

Главная страница Яндекс.Вебмастер.

Для входа в Вебмастер авторизуйтесь в Яндексе

Screaming Frog

Для начала загрузите и установите программу на компьютер. После запуска добавьте URL проверяемого сайта и начните поиск проблем. Неработающие ссылки можно искать даже в бесплатной версии.

Сервис Screaming Frog.

Инструмент SEO-паук в Screaming Frog помогает найти технические неисправности сайта

SiteAnalyzer

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

Страница загрузки SiteAnalyzer.

SiteAnalyzer бесплатно найдёт неработающие URL

Как исправить ошибку Not Found

Выбор конкретного решения зависит от причины ошибки:

  1. Ссылка ведёт в никуда из-за неверного URL. Для решения проблемы замените ошибочную ссылку на правильный адрес, чтобы сервер отдавал код 200 OK.
  2. Битая ссылка. Подобная ситуация не редкость при внутренней перелинковке страниц. К примеру, ссылка есть, а саму страницу давно удалили. Решений два: удалить ссылку или заменить её на другую.

Удалять и менять ссылки вручную удобно только на небольших сайтах. Исправление ошибок на крупных порталах лучше автоматизировать. Например, с помощью специальных плагинов для внутренней перелинковки (Terms Description, Dagon Design Sitemap Generator) и для автоматического формирования адресов страниц (Cyr-To-Lat).

Чтобы ошибки 404 появлялись как можно реже, достаточно соблюдать простые рекомендации:

  • Не присваивайте сложные адреса основным разделам сайта. Это снизит число ошибок, связанных с опечатками в URL.
  • Не меняйте адреса страниц слишком часто. Это неудобно для пользователей и вводит в заблуждение поисковых роботов.
  • Размещайте сайт на надёжном сервере. Это предотвратит ошибки, возникающие из-за неработоспособности сервера.

Мы разобрались, как найти и исправить ошибки Not Found внутри сайта. Но неработающая ссылка может быть расположена и на стороннем ресурсе. Допустим, когда-то на другом сайте разместили рекламную публикацию со ссылкой на определённую страницу. Спустя какое-то время страницу удалили. В этом случае появится ошибка 404. Устранить её можно, связавшись с администрацией ссылающегося сайта. Если же удалить/исправить ссылку нельзя, постарайтесь использовать ошибку с выгодой.

Как сделать страницу 404 полезной

Грамотно оформленная страница с ошибкой Error 404 Not Found — действенный инструмент конвертации посетителей. Ограничений по использованию страницы с ошибкой 404 нет. При этом практически все CMS позволяют настраивать дизайн этой страницы.

Что публиковать на странице 404:

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

При оформлении страницы-ошибки желательно опираться на рекомендации поисковиков:

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

Главное — по возможности отказаться от стандартной страницы 404. Подумайте, как привлечь внимание пользователя. Расскажите ему об отсутствии искомой страницы и предложите взамен что-то полезное или интересное.

Примеры оформления страниц 404

Designzillas

Мультяшная страница креативной студии привлекает внимание и её хочется досмотреть до конца. Если прокрутить страницу, можно увидеть, как из яйца вылупится дракон. При этом на странице есть ссылки на все основные разделы сайта.

404 страница на сайте Designzillas

Меню на сайте Designzillas есть и на 404 странице

Domenart Studio

Веб-студия «Домен АРТ» использует красочную страницу 404, оформленную в единой стилистике ресурса. Заблудившимся пользователям предлагают попробовать ещё раз ввести адрес или перейти в нужный раздел.

Страница 404 Domenart Studio.

Контакты, поиск, меню — и всё это на 404 странице Domenart Studio

E-co

«Эко Пауэр», дистрибьютор производителя источников питания, демонстрирует короткое замыкание как символ ошибки. Посетителям предлагают перейти на главную.

Ошибка 404 «Эко Пауэр»

Ошибка 404 «Эко Пауэр» выглядит как страница входа

Дом со всем

Компания «Дом со всем», занимающаяся бурением скважин, разместила на странице 404 свои контакты и перечень услуг. Со страницы можно перейти в любой раздел сайта или заказать обратный звонок. С таким наполнением посетителю не нужно искать дополнительную информацию где-то ещё.

Страница 404 «Дом со всем».

Компания «Дом со всем» предлагает заказать обратный звонок

Kualo

Страница 404 на веб-хостинге Kualo может заставить пользователя забыть, зачем он сюда пришёл. Увлекательная игра притягивает внимание. В конце игры посетителю предлагают посмотреть сайт хостинга.

Cтраница 404 Kualo

На странице Kualo можно просто поиграть и заработать скидки

Рано или поздно с ошибкой 404 сталкивается большинство сайтов. При регулярной проверке можно своевременно исправить неработающие ссылки, чтобы в ответ пользователи получали код 200 OK. Но для крупного ресурса лучше настроить оригинальную страницу, которая будет отображаться при появлении ошибки Not Found и подскажет посетителям, что делать дальше.

Главные мысли

Ошибка 404 это

В статье мы расскажем, что означает ошибка 404 на сайте. Также она может называться:

  • 404 page not found,
  • http error 404,
  • error 404.

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

404 ошибка (http error 404) — что это значит?

Ошибка 404 page not found — это код ответа сервера. Что это значит?

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

Почему такое может произойти? Есть несколько возможных причин:

  1. Вы допустили ошибку при вводе адреса страницы или при открытии файла в браузере. Или браузеру не удалось найти IP-адрес сервера. Сервер не может найти и выдать данные потому, что вы дали ему неправильные «координаты». В таком случае вам достаточно просто исправить ошибку в URL-адресе, и вместо страницы с ошибкой 404 появятся искомые страница/файл.
  2. Данные (страница или файл) не размещены на сервере, или CMS неверно отвечает на запрос пользователя. В этом случае дело обстоит сложнее и быстро справиться с проблемой не получится. Чтобы устранить ошибку 404, определите, как создавался сайт, на котором обнаружена ошибка (на CMS или без использования CMS). От этого будет зависеть способ решения проблемы.

Мы рассмотрим, что делать с ошибкой 404 и как исправить.


Как убрать ошибку 404 на сайте, созданном на CMS (WordPress, Joomla, 1С-Битрикс и т.д.)

На сайтах, созданных с использованием CMS, встречаются различные страницы с ошибкой 404 (http status 404). В зависимости от типа страницы с ошибкой различаются причины возникновения и пути решения проблемы:

  • Если вы видите на своём сайте стандартную ошибку 404 REG.RU:

В большинстве случаев проблема связана с отсутствием конфигурационного файла .htaccess. Как избавиться от ошибки 404? Создайте в корневой папке сайта пустой текстовый файл с расширением .htaccess и добавьте в него стандартные директивы для используемой CMS. Стандартные директивы приведены в статье: Файлы .htaccess для популярных CMS.

Важно: в панели управления cPanel файл .htaccess по умолчанию скрыт (т.е. он существует, но не виден). Следуйте инструкции, чтобы включить отображение файла. Затем сверьте его содержимое со стандартным.

Если файл .htaccess существует и его содержимое корректно, а ошибка 404 not found сохраняется, обратитесь в техническую поддержку.

  • Если вы видите иную страницу ошибки, которую отдает CMS сайта. Например:


Ошибка на WordPress


Пользовательская ошибка 404 not found

Возможно, страница не создана или не опубликована на этапе размещения сайта в админке CMS. Также ошибка может быть связана с формированием «человекопонятных» ЧПУ-ссылок с помощью SEO-плагинов. Чтобы избавиться от проблемы, необходимо обратиться к веб-разработчикам сайта или на тематические форумы, на которых представлена необходимая техническая информация (ошибка http 404).


Как быстро устранить ошибку 404 на сайте, созданном без использования CMS

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

Что означает это сообщение? Запрашиваемые страница/файл отсутствуют или размещены в неправильной папке (не в корневой папке сайта).

Что делать? Откройте корневую папку сайта в панели управления хостингом и проверьте, находятся ли в ней файлы вашего сайта.

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

Как находить и мониторить код ошибки 404?

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

  • Яндекс.Вебмастер,
  • Google Search Console,
  • Screaming Frog.

Ниже мы описали, как работать с каждым из них.


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

  1. Авторизуйтесь в Яндекс.Вебмастер.

  2. Перейдите в раздел Индексирование — Страницы в поиске:


HTTP status 404 — что это

  1. Выберите Исключенные страницы:
  1. Добавьте фильтр, при котором отобразятся результаты с ошибкой «404 page not found»:


Google Search Console

  1. Авторизуйтесь в Google Search Console.

  2. Разверните блок Индекс и выберите Покрытие:


404 ошибка: что это

  1. Используйте фильтр, который покажет код ошибки 404. Для этого перейдите в раздел Сведения и кликните Отправленный URL не найден (ошибка 404):


Ошибка 404: что значит и как исправить


Screaming Frog

  1. Загрузите программу с официального сайта.

  2. Установите её на компьютер.

  3. Откройте программу, введите ссылку на сайт и нажмите Start:

  1. Перейдите во вкладку Response Code. Из выпадающего списка выберите фильтр Client Error (4xx):

Открывается только главная страница сайта, на внутренних страницах ошибка 404 или 500

Рассмотрим, что значит и как исправить ошибку отображения внутренних страниц сайта (error 404 или 500). Причиной проблемы является отсутствие файла .htaccess (либо он пустой, либо в нем не хватает необходимых директив для работы CMS). Решить проблему может замена текущего файла .htaccess стандартным для данной CMS.

На хостинге Linux

Если у вас ISPmanager, проверьте, не включены ли Автоподдомены. Если они включены, отключите их, проверьте актуальность проблемы.

В остальных случаях для устранения внутренней ошибки 404 или 500, перейдите в корневую папку сайта: Как узнать корневую папку сайта
Создайте файл .htaccess (или замените его) со следующим содержимым:


Файл .htaccess для Joomla

##

# @version $Id: htaccess.txt 14401 2010-01-26 14:10:00Z louis $
# @package Joomla
# @copyright Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
# @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
# Joomla! is Free Software
##
#####################################################
#  READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE
#
# The line just below this section: 'Options +FollowSymLinks' may cause problems
# with some server configurations.  It is required for use of mod_rewrite, but may already
# be set by your server administrator in a way that dissallows changing it in
# your .htaccess file.  If using it causes your server to error out, comment it out (add # to
# beginning of line), reload your site in your browser and test your sef url's.  If they work,
# it has been set by your server administrator and you do not need it set here.
#
#####################################################

##  Can be commented out if causes errors, see notes above.
Options +FollowSymLinks

#
#  mod_rewrite in use

RewriteEngine On

########## Begin - Rewrite rules to block out some common exploits
## If you experience problems on your site block out the operations listed below
## This attempts to block the most common type of exploit `attempts` to Joomla!
#
## Deny access to extension xml files (uncomment out to activate)
#<Files ~ ".xml$">
#Order allow,deny
#Deny from all
#Satisfy all
#</Files>
## End of deny access to extension xml files
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|%3D) [OR]
# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*(.*) [OR]
# Block out any script that includes a <script> tag in URL
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})
# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ index.php [F,L]
#
########## End - Rewrite rules to block out some common exploits

#  Uncomment following line if your webserver's URL
#  is not directly related to physical file paths.
#  Update Your Joomla! Directory (just / for root)

# RewriteBase /


########## Begin - Joomla! core SEF Section
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|.php|.html|.htm|.feed|.pdf|.raw|/[^.]*)$  [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
#
########## End - Joomla! core SEF Section


Файл .htaccess для WordPress

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress


Файл .htaccess для HostCMS

Options +FollowSymlinks
AddDefaultCharset Off

<IfModule mod_php4.c>

 php_flag magic_quotes_gpc off

 php_flag magic_quotes_runtime off

 php_flag register_globals off

</IfModule>

<IfModule mod_php5.c>

 php_flag magic_quotes_gpc off

 php_flag magic_quotes_runtime off
 php_flag register_globals off
</IfModule>
<IfModule mod_dir.c>
 DirectoryIndex index.php index.htm index.html
</IfModule>
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ /index.php
</IfModule>


Файл .htaccess для Bitrix

Options -Indexes 

ErrorDocument 404 /404.php


<IfModule mod_php5.c>

  php_flag allow_call_time_pass_reference 1

  php_flag session.use_trans_sid off

  #php_value display_errors 1

  #php_value mbstring.func_overload 2
  #php_value mbstring.internal_encoding UTF-8
</IfModule>

<IfModule mod_rewrite.c>
  Options +FollowSymLinks
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !/bitrix/urlrewrite.php$
  RewriteRule ^(.*)$ /bitrix/urlrewrite.php [L]
  RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]
</IfModule>

<IfModule mod_dir.c>
  DirectoryIndex index.php index.html
</IfModule>

<IfModule mod_expires.c>
  ExpiresActive on
  ExpiresByType image/jpeg "access plus 3 day"
  ExpiresByType image/gif "access plus 3 day"
</IfModule>


Файл .htaccess для ModX

# MODx supports Friendly URLs via this .htaccess file. You must serve web

# pages via Apache with mod_rewrite to use this functionality, and you must

# change the file name from ht.access to .htaccess.

#

# Make sure RewriteBase points to the directory where you installed MODx.

# E.g., "/modx" if your installation is in a "modx" subdirectory.

#

# You may choose to make your URLs non-case-sensitive by adding a NC directive

# to your rule: RewriteRule ^(.*)$ index.php?q=$1 [L,QSA,NC]

RewriteEngine On
RewriteBase /

# Rewrite www.domain.com -> domain.com -- used with SEO Strict URLs plugin
#RewriteCond %{HTTP_HOST} .
#RewriteCond %{HTTP_HOST} !^example-domain-please-change.com [NC]
#RewriteRule (.*) http://example-domain-please-change.com/$1 [R=301,L]
#
# or for the opposite domain.com -> www.domain.com use the following
# DO NOT USE BOTH
#
#RewriteCond %{HTTP_HOST} .
#RewriteCond %{HTTP_HOST} !^www.example-domain-please-change.com [NC]
#RewriteRule (.*) http://www.example-domain-please-change.com/$1 [R=301,L]
#
# Rewrite secure requests properly to prevent SSL cert warnings, e.g. prevent 
# https://www.domain.com when your cert only allows https://secure.domain.com
#RewriteCond %{SERVER_PORT} !^443
#RewriteRule (.*) https://example-domain-please-change.com.com/$1 [R=301,L]
#
# The Friendly URLs part
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
#
# Make sure .htc files are served with the proper MIME type, which is critical # for XP SP2. Un-comment if your host allows htaccess MIME type overrides.
#AddType text/x-component .htc
#
# If your server is not already configured as such, the following directive
# should be uncommented in order to set PHP's register_globals option to OFF.
# This closes a major security hole that is abused by most XSS (cross-site
# scripting) attacks. For more information: http://php.net/register_globals
#
# To verify that this option has been set to OFF, open the Manager and choose
# Reports -> System Info and then click the phpinfo() link. Do a Find on Page
# for "register_globals". The Local Value should be OFF. If the Master Value
# is OFF then you do not need this directive here.
#
# IF REGISTER_GLOBALS DIRECTIVE CAUSES 500 INTERNAL SERVER ERRORS :
#
# Your server does not allow PHP directives to be set via .htaccess. In that
# case you must make this change in your php.ini file instead. If you are
# using a commercial web host, contact the administrators for assistance in
# doing this. Not all servers allow local php.ini files, and they should
# include all PHP configurations (not just this one), or you will effectively
# reset everything to PHP defaults. Consult www.php.net for more detailed
# information about setting PHP directives.
#
#php_flag register_globals Off
#
# For servers that support output compression, you should pick up a bit of
# speed by un-commenting the following lines.
#
#php_flag zlib.output_compression On
#php_value zlib.output_compression_level 5
#
# The following directives stop screen flicker in IE on CSS rollovers. If
# needed, un-comment the following rules. When they're in place, you may have
# to do a force-refresh in order to see changes in your designs.
#
#ExpiresActive On
#ExpiresByType image/gif A2592000
#ExpiresByType image/jpeg A2592000
#ExpiresByType image/png A2592000
#BrowserMatch "MSIE" brokenvary=1
#BrowserMatch "Mozilla/4.[0-9]{2}" brokenvary=1
#BrowserMatch "Opera" !brokenvary
#SetEnvIf brokenvary 1 force-no-vary


Файл .htaccess для Drupal

#

# Apache/PHP/Drupal settings:

#


# Protect files and directories from prying eyes.

<FilesMatch ".(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(.php)?|xtmpl)$|^(..*|Entries.*|Repository|Root|Tag|Template)$">

  Order allow,deny

</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Force simple error message for requests for non-existent favicon.ico.
<Files favicon.ico>
  # There is no end quote below, for compatibility with Apache 1.3.
  ErrorDocument 404 "The requested file favicon.ico was not found.
</Files>

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_initialize_variables() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch .php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess, because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)." - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} !^www. [NC]
  # RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www.(.+)$ [NC]
  # RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Pass all requests not referring directly to files in the filesystem to
  # index.php. Clean URLs are handled in drupal_environment_initialize().
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}.gz -s
    RewriteRule ^(.*).css $1.css.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}.gz -s
    RewriteRule ^(.*).js $1.js.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule .css.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule .js.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(.js.gz|.css.gz)$">
      # Serve correct encoding type.
      Header append Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>


Файл .htaccess для NetCat

AddDefaultCharset windows-1251
ErrorDocument 404 /netcat/require/e404.php
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ /netcat/require/e404.php?REQUEST_URI=$1 [L,QSA]
</ifModule>


Файл .htaccess для DLE

DirectoryIndex index.php
RewriteEngine On
RewriteBase /
# Редиректы
RewriteRule ^page/(.*)$ index.php?cstart=$1 [L]
# Сам пост
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/page,([0-9]+),([0-9]+),(.*).html(/?)+$ index.php?subaction=showfull&year=$1&month=$2&day=$3&news_page=$4&cstart=$5&news_name=$6 [L]
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/page,([0-9]+),(.*).html(/?)+$ index.php?subaction=showfull&year=$1&month=$2&day=$3&news_page=$4&news_name=$5 [L]
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/print:page,([0-9]+),(.*).html(/?)+$ engine/print.php?subaction=showfull&year=$1&month=$2&day=$3&news_page=$4&news_name=$5 [L]
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/(.*).html(/?)+$ index.php?subaction=showfull&year=$1&month=$2&day=$3&news_name=$4 [L]
RewriteRule ^([^.]+)/page,([0-9]+),([0-9]+),([0-9]+)-(.*).html(/?)+$ index.php?newsid=$4&news_page=$2&cstart=$3&seourl=$5&seocat=$1 [L]
RewriteRule ^([^.]+)/page,([0-9]+),([0-9]+)-(.*).html(/?)+$ index.php?newsid=$3&news_page=$2&seourl=$4&seocat=$1 [L]
RewriteRule ^([^.]+)/print:page,([0-9]+),([0-9]+)-(.*).html(/?)+$ engine/print.php?news_page=$2&newsid=$3&seourl=$4&seocat=$1 [L]
RewriteRule ^([^.]+)/([0-9]+)-(.*).html(/?)+$ index.php?newsid=$2&seourl=$3&seocat=$1 [L]
RewriteRule ^page,([0-9]+),([0-9]+),([0-9]+)-(.*).html(/?)+$ index.php?newsid=$3&news_page=$1&cstart=$2&seourl=$4 [L]
RewriteRule ^page,([0-9]+),([0-9]+)-(.*).html(/?)+$ index.php?newsid=$2&news_page=$1&seourl=$3 [L]
RewriteRule ^print:page,([0-9]+),([0-9]+)-(.*).html(/?)+$ engine/print.php?news_page=$1&newsid=$2&seourl=$3 [L]
RewriteRule ^([0-9]+)-(.*).html(/?)+$ index.php?newsid=$1&seourl=$2 [L]

# За день
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})(/?)+$ index.php?year=$1&month=$2&day=$3 [L]
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/page/([0-9]+)(/?)+$ index.php?year=$1&month=$2&day=$3&cstart=$4 [L]
# За весь месяц
RewriteRule ^([0-9]{4})/([0-9]{2})(/?)+$ index.php?year=$1&month=$2 [L]
RewriteRule ^([0-9]{4})/([0-9]{2})/page/([0-9]+)(/?)+$ index.php?year=$1&month=$2&cstart=$3 [L]
# Вывод за весь год
RewriteRule ^([0-9]{4})(/?)+$ index.php?year=$1 [L]
RewriteRule ^([0-9]{4})/page/([0-9]+)(/?)+$ index.php?year=$1&cstart=$2 [L]
# вывод отдельному тегу
RewriteRule ^tags/([^/]*)(/?)+$ index.php?do=tags&tag=$1 [L]
RewriteRule ^tags/([^/]*)/page/([0-9]+)(/?)+$ index.php?do=tags&tag=$1&cstart=$2 [L]
# вывод для отдельного юзера
RewriteRule ^user/([^/]*)/rss.xml$ engine/rss.php?subaction=allnews&user=$1 [L]
RewriteRule ^user/([^/]*)(/?)+$ index.php?subaction=userinfo&user=$1 [L]
RewriteRule ^user/([^/]*)/page/([0-9]+)(/?)+$ index.php?subaction=userinfo&user=$1&cstart=$2 [L]
RewriteRule ^user/([^/]*)/news(/?)+$ index.php?subaction=allnews&user=$1 [L]
RewriteRule ^user/([^/]*)/news/page/([0-9]+)(/?)+$ index.php?subaction=allnews&user=$1&cstart=$2 [L]
RewriteRule ^user/([^/]*)/news/rss.xml(/?)+$ engine/rss.php?subaction=allnews&user=$1 [L]
# вывод всех последних новостей
RewriteRule ^lastnews/(/?)+$ index.php?do=lastnews [L]
RewriteRule ^lastnews/page/([0-9]+)(/?)+$ index.php?do=lastnews&cstart=$1 [L]
# вывод в виде каталога
RewriteRule ^catalog/([^/]*)/rss.xml$ engine/rss.php?catalog=$1 [L]
RewriteRule ^catalog/([^/]*)(/?)+$ index.php?catalog=$1 [L]
RewriteRule ^catalog/([^/]*)/page/([0-9]+)(/?)+$ index.php?catalog=$1&cstart=$2 [L]
# вывод непрочитанных статей
RewriteRule ^newposts(/?)+$ index.php?subaction=newposts [L]
RewriteRule ^newposts/page/([0-9]+)(/?)+$ index.php?subaction=newposts&cstart=$1 [L]
# вывод избранных статей
RewriteRule ^favorites(/?)+$ index.php?do=favorites [L]
RewriteRule ^favorites/page/([0-9]+)(/?)+$ index.php?do=favorites&cstart=$1 [L]
RewriteRule ^rules.html$ index.php?do=rules [L]
RewriteRule ^statistics.html$ index.php?do=stats [L]
RewriteRule ^addnews.html$ index.php?do=addnews [L]
RewriteRule ^rss.xml$ engine/rss.php [L]
RewriteRule ^sitemap.xml$ uploads/sitemap.xml [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]+)/page/([0-9]+)/$ index.php?do=cat&category=$1&cstart=$2 [L]
RewriteRule ^([^.]+)/$ index.php?do=cat&category=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)/rss.xml$ engine/rss.php?do=cat&category=$1 [L]
RewriteRule ^page,([0-9]+),([^/]+).html$ index.php?do=static&page=$2&news_page=$1 [L]
RewriteRule ^print:([^/]+).html$ engine/print.php?do=static&page=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+).html$ index.php?do=static&page=$1 [L]


Файл .htaccess для Opencart

Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]


Файл .htaccess для Webasyst

<FilesMatch ".md5$">
Deny from all
</FilesMatch>
DirectoryIndex index.php
Options -Indexes
# Comment the following line, if option Multiviews not allowed here
Options -MultiViews
AddDefaultCharset utf-8
<ifModule mod_rewrite.c>
RewriteEngine On
# Uncomment the following line, if you are having trouble
RewriteBase /
RewriteCond %{REQUEST_URI} !.(js|css|jpg|jpeg|gif|png|svg|ttf|eot|otf|woff|woff2)$ [or]
RewriteCond %{REQUEST_URI} apple-touch-icon.png$ [or]
RewriteCond %{REQUEST_METHOD} ^(POST|PUT|COPY|MOVE|DELETE|PROPFIND|OPTIONS|MKCOL)$ [or]
RewriteCond %{HTTP:Translate} ^.+$ [or]
RewriteCond %{HTTP_USER_AGENT} ^(DavClnt|litmus|gvfs|davfs|wdfs|WebDAV|cadaver|Cyberduck)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,QSA]
</ifModule>
<ifModule mod_headers.c>
<FilesMatch ".(jpg|jpeg|png|gif|js|css|svg|ttf|eot|otf|woff|woff2)$">
Header set Cache-Control "max-age=3153600, public"
</FilesMatch>
</ifModule>

Если у вас хостинг Windows

На хостинге Windows файл .htaccess не поддерживается. Его функцию выполняет файл web.config. Если вы наблюдаете внутреннюю ошибку 404 или 500 на хостинге Windows, рекомендуем обратиться к разработчикам сайта или на тематические форумы с вопросом, как убрать 404, заменив файл web.config.

Что будет, если не исправлять ошибку 404

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

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

Сделайте страницу 404 полезной

Ошибка 404 (страница не найдена) может появиться в любое время. Важно, чтобы пользователь при входе на эту страницу не потерял доверия к сайту. Страницы с ошибкой 404 можно создавать самостоятельно. Например, если у вас сайт на WordPress или вы пользуетесь услугой REG.Site, страницу с ошибкой можно легко создать с помощью плагина 404page.

Вот несколько советов по созданию страницы:

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

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

Если перечисленные способы не помогли исправить ошибку, обратитесь в службу поддержки REG.RU.

Видеосправка. Об ошибке 404 и как создать страницу для неё

Page semi-protected

From Wikipedia, the free encyclopedia

In computer network communications, the HTTP 404, 404 not found, 404, 404 error, page not found or file not found error message is a hypertext transfer protocol (HTTP) standard response code, to indicate that the browser was able to communicate with a given server, but the server could not find what was requested. The error may also be used when a server does not wish to disclose whether it has the requested information.[1]

The website hosting server will typically generate a «404 Not Found» web page when a user attempts to follow a broken or dead link; hence the 404 error is one of the most recognizable errors encountered on the World Wide Web.

English Wikipedia’s 404 Page

Overview

When communicating via HTTP, a server is required to respond to a request, such as a web browser request for a web page, with a numeric response code and an optional, mandatory, or disallowed (based upon the status code) message. In code 404, the first digit indicates a client error, such as a mistyped Uniform Resource Locator (URL). The following two digits indicate the specific error encountered. HTTP’s use of three-digit codes is similar to the use of such codes in earlier protocols such as FTP and NNTP. At the HTTP level, a 404 response code is followed by a human-readable «reason phrase». The HTTP specification suggests the phrase «Not Found»[1] and many web servers by default issue an HTML page that includes both the 404 code and the «Not Found» phrase.

A 404 error is often returned when pages have been moved or deleted. In the first case, it is better to employ URL mapping or URL redirection by returning a 301 Moved Permanently response, which can be configured in most server configuration files, or through URL rewriting; in the second case, a 410 Gone should be returned. Because these two options require special server configuration, most websites do not make use of them.

404 errors should not be confused with DNS errors, which appear when the given URL refers to a server name that does not exist. A 404 error indicates that the server itself was found, but that the server was not able to retrieve the requested page.

Soft 404 errors

Some websites report a «not found» error by returning a standard web page with a «200 OK» response code, falsely reporting that the page loaded properly; this is known as a soft 404. The term «soft 404» was introduced in 2004 by Ziv Bar-Yossef et al.[2]

Soft 404s are problematic for automated methods of discovering whether a link is broken. Some search engines, like Yahoo and Google, use automated processes to detect soft 404s.[3] Soft 404s can occur as a result of configuration errors when using certain HTTP server software, for example with the Apache software, when an Error Document 404 (specified in a .htaccess file) is specified as an absolute path (e.g. http://example.com/error.html) rather than a relative path (/error.html).[4] This can also be done on purpose to force some browsers (like Internet Explorer) to display a customized 404 error message rather than replacing what is served with a browser-specific «friendly» error message (in Internet Explorer, this behavior is triggered when a 404 is served and the received HTML is shorter than a certain length, and can be manually disabled by the user).

There are also «soft 3XX» errors where content is returned with a status 200 but comes from a redirected page, such as when missing pages are redirected to the domain root/home page.

Proxy servers

Some proxy servers generate a 404 error when a 500-range error code would be more correct. If the proxy server is unable to satisfy a request for a page because of a problem with the remote host (such as hostname resolution failures or refused TCP connections), this should be described as a 5xx Internal Server Error, but might deliver a 404 instead. This can confuse programs that expect and act on specific responses, as they can no longer easily distinguish between an absent web server and a missing web page on a web server that is present.

Intentional 404s

In July 2004, the UK telecom provider BT Group deployed the Cleanfeed content blocking system, which returns a 404 error to any request for content identified as potentially illegal by the Internet Watch Foundation.[5] Other ISPs return a HTTP 403 «forbidden» error in the same circumstances.[6] The practice of employing fake 404 errors as a means to conceal censorship has also been reported in Thailand[7] and Tunisia.[8] In Tunisia, where censorship was severe before the 2011 revolution, people became aware of the nature of the fake 404 errors and created an imaginary character named «Ammar 404» who represents «the invisible censor».[9]

Microsoft Internet Server 404 substatus error codes

The webserver software developed by Microsoft, Microsoft’s Internet Information Services (IIS), returns a set of substatus codes with its 404 responses. The substatus codes take the form of decimal numbers appended to the 404 status code. The substatus codes are not officially recognized by IANA and are not returned by non-Microsoft servers.

Substatus codes

Microsoft’s IIS 7.0, IIS 7.5, and IIS 8.0 servers define the following HTTP substatus codes to indicate a more specific cause of a 404 error:

  • 404.0 – Not found.
  • 404.1 – Site Not Found.
  • 404.2 – ISAPI or CGI restriction.
  • 404.3 – MIME type restriction.
  • 404.4 – No handler configured.
  • 404.5 – Denied by request filtering configuration.
  • 404.6 – Verb denied.
  • 404.7 – File extension denied.
  • 404.8 – Hidden namespace.
  • 404.9 – File attribute hidden.
  • 404.10 – Request header too long.
  • 404.11 – Request contains double escape sequence.
  • 404.12 – Request contains high-bit characters.
  • 404.13 – Content length too large.
  • 404.14 – Request URL too long.
  • 404.15 – Query string too long.
  • 404.16 – DAV request sent to the static file handler.
  • 404.17 – Dynamic content mapped to the static file handler via a wildcard MIME mapping.
  • 404.18 – Query string sequence denied.
  • 404.19 – Denied by filtering rule.
  • 404.20 – Too Many URL Segments.

Custom error pages

The Wikimedia 404 message

Web servers can typically be configured to display a customised 404 error page, including a more natural description, the parent site’s branding, and sometimes a site map, a search form or 404-page widget. The protocol level phrase, which is hidden from the user, is rarely customized. Internet Explorer, however, will not display custom pages unless they are larger than 512 bytes, opting instead to display a «friendly» error page.[10] Google Chrome included similar functionality, where the 404 is replaced with alternative suggestions generated by Google algorithms, if the page is under 512 bytes in size.[11] Another problem is that if the page does not provide a favicon, and a separate custom 404-page exists, extra traffic and longer loading times will be generated on every page view.[12][13]

Many organizations use 404 error pages as an opportunity to inject humor into what may otherwise be a serious website. For example, Metro UK shows a polar bear on a skateboard, and the web development agency Left Logic has a simple drawing program.[14] During the 2015 UK general election campaign the main political parties all used their 404 pages to either take aim at political opponents or show relevant policies to potential supporters.[15] In Europe, the NotFound project, created by multiple European organizations including Missing Children Europe and Child Focus, encourages site operators to add a snippet of code to serve customized 404 error pages[16] which provide data about missing children.[17]

While many websites send additional information in a 404 error message—such as a link to the homepage of a website or a search box—some also endeavor to find the correct web page the user wanted. Extensions are available for some content management systems (CMSs) to do this.[18]

Tracking 404 errors

A number of tools exist that crawl through a website to find pages that return 404 status codes. These tools can be helpful in finding links that exist within a particular website. The limitation of these tools is that they only find links within one particular website, and ignore 404s resulting from links on other websites. As a result, these tools miss out on 83% of the 404s on websites.[19] One way around this is to find 404 errors by analyzing external links.[20]

One of the most effective ways to discover 404 errors is by using Google Search Console, Google Analytics or crawling software.

Another common method is tracking traffic to 404 pages using log file analysis.[21] This can be useful to understand more about what 404s users reached on the site. Another method of tracking traffic to 404 pages is using JavaScript-based traffic tracking tools.[22]

See also

  • Blue screen of death
  • Funky caching
  • Link rot
  • List of HTTP status codes

References

  1. ^ a b Fielding, R.; Reschke, J. (June 2014). Fielding, R; Reschke, J (eds.). «RFC 7231, HTTP/1.1 Semantics and Content, Section 6.5.4 404 Not Found». ietf.org. doi:10.17487/RFC7231. S2CID 14399078. Retrieved 13 December 2018.
  2. ^ Ziv Bar-Yossef; Andrei Z. Broder; Ravi Kumar; Andrew Tompkins (2004). Sic Transit Gloria Telae: Towards an Understanding of the Web’s Decay. Proceedings of the 13th International Conference on World Wide Web (WWW). pp. 328–337. doi:10.1145/988672.988716. ISBN 978-1581138443. S2CID 587547.
  3. ^ «Why is your crawler asking for strange URLs that have never existed on my site?». Yahoo Ysearch Help page. Archived from the original on 15 July 2014. Retrieved 4 September 2013.
  4. ^ «Farewell to soft 404s». Google Official Blog. Retrieved 20 September 2008.
  5. ^ «LINX Public Affairs » Cleanfeed: the facts». Publicaffairs.linx.net. 10 September 2004. Archived from the original on 13 May 2011. Retrieved 6 March 2011.
  6. ^ «DEMON – Error 403». Retrieved 14 June 2012.
  7. ^ Sambandaraksa, Don (18 February 2009). «The old fake ‘404 Not Found’ routine — Dead link». Bangkok Post. Retrieved 12 September 2010.
  8. ^ Noman, Helmi (12 September 2008). «Tunisian journalist sues government agency for blocking Facebook, claims damage for the use of 404 error message instead of 403». Open Net Initiative. Retrieved 21 November 2010.
  9. ^ «Anti-censorship movement in Tunisia: creativity, courage and hope!». Global Voices Advocacy. 27 May 2010. Retrieved 28 August 2010.
  10. ^ «Friendly HTTP Error Pages». msdn.com. 18 August 2010. Archived from the original on 2 December 2010. Retrieved 14 June 2012.
  11. ^ «Issue 1695: Chrome needs option to turn off «Friendly 404″ displays». bugs.chromium.org. Retrieved 25 December 2021.
  12. ^ Heng, Christopher (7 September 2008). «What is Favicon.ico and How to Create a Favicon Icon for Your Website». The Site Wizard. Retrieved 23 February 2011.
  13. ^ «The Dastardly «favicon.ico not found» Error». Internet Folks. 3 August 1999.
  14. ^ «From skateboarding bears to missing children: The power of the 404 Not Found error page». Metro. 6 June 2011. Retrieved 16 April 2013.
  15. ^ «The political Page 404 war». BBC Newsbeat. 27 April 2015. Retrieved 18 May 2018.
  16. ^ «Notfound.org». notfound. notfound. Archived from the original on 2 September 2014.
  17. ^ «Missing children messages go on 404 error pages». BBC News. 27 September 2012. Retrieved 20 September 2014.
  18. ^ Swenson, Sahala (19 August 2008). «Make your 404 pages more useful». Official Google Webmaster Central Blog. Google, Inc. Retrieved 28 August 2009.
  19. ^ «Sources Leading To 404s». SpringTrax. Retrieved 11 February 2013.
  20. ^ Cushing, Anne (2 April 2013). «A Data-Centric Approach To Identifying 404 Pages Worth Saving». Search Engine Land. Retrieved 7 June 2013.
  21. ^ «Tracking and Preventing 404 Errors». 404errorpages.com. Retrieved 7 June 2013.
  22. ^ «Understand 404 Errors». SpringTrax.com. Retrieved 7 June 2013.

External links

  • A More Useful 404
  • 404 Not Found of the Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content specification, at the Internet Engineering Task Force
  • ErrorDocument Directive – instructions on custom error pages for the Apache 2.0 web server
  • 404: Not Found – an award-winning song about the error code

Of the many potential errors you might see on your WordPress site, Error 404 Not Found is one of the tamer ones. But that doesn’t mean it isn’t frustrating when you or your visitors try to browse your site and keep running into the Error 404 Not Found message. 😒 That’s the last thing you want first-time potential customers seeing from your brand. A 404 error can also be an indicator to you that something has changed or moved and a 301 redirect probably needs to be added for SEO.

In this post, we’re going to try to help you get your site working again by explaining a few things:

Prefer to watch the video version?

What is the Error 404 Not Found?

The Internet Engineering Task Force (IETF) defines the error 404 Not Found as:

The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists. A 404 status code does not indicate whether this lack of representation is temporary or permanent; the 410 (Gone) status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent.

Whenever you, or one of your visitors, visit your website, your browser sends a request to the web server and receives back data including something called an HTTP header. The HTTP header includes HTTP status codes to explain “what happened” with the request.

Most of the time, the request works perfectly and you never actually see the HTTP status code (unless you go looking). But if something goes wrong, your web browser will usually display a message with the HTTP status code to indicate the exact problem.

Just like other error messages (500 error, 502 error, 503 error, 504 error, etc.), the Error 404 Not Found message is the result of that process.

What Does Error 404 Not Found Actually Mean?

Basically, it means that the client (your, or your visitor’s, web browser) was able to successfully connect to the host (your website’s server), but it was unable to find the actual resource that was requested (e.g. a specific URL or filename).

For example, if someone tries to access yoursite.com/post-name but you don’t have any content with the slug post-name. The visitor will then see a 404 error because, even though your web server is functioning normally, the resource that was requested doesn’t exist.

It’s not just posts or pages either, any asset missing can generate a 404 error on the server, such as a missing image file, missing JavaScript, missing CSS, etc.

What Causes Error 404 Not Found on WordPress?

If you see this error on all of your site’s content, it’s typically due to an issue with your WordPress site’s permalinks. If you only see it on individual pieces of content, though, it’s most likely because you changed a piece of content’s slug without setting up a redirect.

Additionally, the 404 error isn’t always a bad thing – it’s only bad when it’s interfering with usability. And sometimes things are just out of your control!

For example, sometimes a person might just type the wrong URL in their address bar. In that case, they’ll still see a 404 error, but there’s no actual problem with how your site is configured. This is actually the desired response, and you can create your own custom 404 page to help get visitors to the right spot (we’ll show you how later on).

Error 404 Not Found Variations

Because different browsers display error messages differently, you might see a different message for this error. Other common variations include:

  • “Error 404”
  • “404 Not Found”
  • “HTTP Error 404”
  • “Not Found”
  • “Page Not Found”
  • “The requested URL was not found on this server.”
  • “The page cannot be found”
  • “We can’t find the page you’re looking for.”
  • “The requested URL /~ was not found on this server. That’s all we know.

Google 404 error page

Google 404 error page

The Error 404 Not Found message is also unique in that many sites will actually create a custom page to address the error, rather showing one of the messages above. Some WordPress themes also include custom 404 pages by default. For that reason, you might not actually see the error message at all because many sites will use funny or creative 404 pages instead.

Funny 404 page example

Funny 404 page example

Below is an example of our own 404 page at Kinsta. We include a search box and some of our recent blog posts to help visitors find what they might have been looking for. Always include search functionality on your 404 page.

Kinsta 404 page

Kinsta 404 page

Error 404 Not Found Impact on SEO

Error 404 Not Found doesn’t have any inherent negative impact on SEO. But it might have a negative impact depending on the reason for why the error is happening.

For example, if a visitor just mistypes a URL and sees a 404 error – there won’t be a negative impact on SEO. But if you have individual errors because of broken URLs, that will inhibit Google’s ability to properly crawl your site and have a negative SEO effect in that way.

Additionally, if a permalink issue is causing sitewide 404 errors, Google won’t be able to crawl any of your site’s content. In other words, always fix your 404 errors as soon as possible.

Error 404 Not Found Impact on Site Performance

Many don’t realize it, but sites that generate a lot of 404 errors can easily run into performance issues, as these responses aren’t typically cached. We saw this a lot on larger sites and it can be a big problem if you accidentally promote or get a surge of viral traffic to a 404 page. To minimize the impact of 404 requests on site performance, we automatically cache 404 pages for 15 minutes. If you create a new page with the same URL as the cached 404 page, we’ll automatically purge the cache so your visitors will be able to see the new page immediately. This means your site will be protected from PHP and CPU spikes caused by traffic to dynamic 404 pages.

You are probably generating more 404 errors than you think! Our MyKinsta analytics tool can help you determine the exact amount (as seen below).

404 Errors

404 Errors

You can also quickly see what the top 404 errors are. In this example below, you can see the site is missing some mobile icons, such as /apple-touch-icon.png. These are most likely in a theme or plugin’s code that is getting queried, but the actual icons were never added. Therefore, the server generates a 404 error as it can’t find the resources.

Top 404 errors

Top 404 errors

You can also check 404 errors in Google Search Console or install a third-party plugin such as Redirection which logs 404 errors. However, remember that plugins like these also have an impact on performance. It’s much better to rely on a server-level tool. That’s why we provide these tools for all Kinsta clients.

The reason these errors are bad is that many 404 pages are very resource intensive. For large sites, you’ll want to avoid a heavy 404 page. Create a simple 404 template that avoids querying the database any further if possible.

How to Fix Error 404 Not Found on WordPress

Below, we’ll cover a couple different methods for how to fix the Error 404 Not Found message, depending on whether it’s happening sitewide or to specific content.

Update Your WordPress Site’s Permalinks

If you’re experiencing sitewide 404 errors when trying to access content, the most likely cause is an issue with your permalinks (or your .htaccess file, if your host uses Apache). If you’re a Kinsta client, we utilize Nginx, so you can rule out the .htaccess file as a possible cause.

The easiest way to fix this is to update your permalink settings through the WordPress dashboard. All you need to do is go to Settings → Permalinks and click Save Changes (you don’t need to make any changes – clicking Save Changes is enough).

Regenerate permalinks in WordPress

Regenerate permalinks in WordPress

Set Up 301 Redirects For Moved or Renamed Content

If you’re experiencing 404 errors on a specific piece of content, the issue is likely that you:

  • Changed the URL slug for that content.
  • Moved that piece of content manually, e.g. by deleting the existing post and pasting it into a new post.

Users then try to access the content at the old location and see a 404 page instead of the resource they were expecting. The best way to fix this is to automatically redirect anyone who tries to access the old location to the new location. That way, they’ll make it to the right spot without any 404 errors. It’s also good for SEO. If you move or rename a post without adding a redirect, you lose all the domain authority attached to the backlinks pointed at that post.

WordPress by default will attempt to redirect changed/moved content. But it doesn’t always work and you should never rely on WordPress for this functionality. But don’t worry, there are several easy ways to set up redirects in WordPress:

First, you can use the free Redirection plugin to manage redirects from your WordPress dashboard. Once you’ve installed and activated the plugin, go to Tools → Redirection and enter the 404 page URL in the Source URL box and the new location of the content in the Target URL box:

How to set up redirects with the Redirection plugin

How to set up redirects with the Redirection plugin

If you’re hosting with Kinsta, you can also manage redirects from the MyKinsta dashboard. Using Kinsta’s tool is actually a better way to go about it as the rules are implemented at the server level, which is a much more optimal way in terms of performance. It also means one less third-party plugin you have to worry about.

Go to the site you want to manage. Then, click on the “Redirects” tab. To add a new redirect, click the large “Add Redirect Rule” button:

How to set up redirects from your Kinsta dashboard

How to set up redirects from your Kinsta dashboard

Finally, if your host uses the Apache server, you can use .htaccess to set up redirects. The .htaccess Generator site can help you generate the proper code to add to your site’s .htaccess file.

How to Create Your Own Error 404 Not Found Page

While you can do your best to prevent 404 errors by following the tips above, it’s impossible to entirely eliminate 404 errors because some things are just plain outside your control. It’s not uncommon for small WordPress sites to have thousands of 404 errors every month.

For example, if a visitor mistypes the URL, or if another website links to a page that doesn’t exist, people are going to get 404 errors no matter what.

To provide a more user-friendly error page, you can use one of the many 404 page plugins. For example, the free 404page plugin lets you set up a custom 404 error page with:

  • A search box
  • Important links
  • Contact information

Another important feature of the 404page plugin is that it doesn’t create redirects. A 404 page should never be redirected to a physical page such as yoursite.com/404. The 404 error should always be generated dynamically on the page in question.

By including these elements, you give visitors the tools they need to find their way to the right page. But remember, keep your 404 page light for better performance. Only include what is absolutely needed.

How to Monitor 404 Errors Going Forward

Going forward, it can be beneficial to pay attention to which requests are causing 404 errors at your site. This can help you:

  • Find broken links that are sending people to a non-existent resource (these could be internal links or external links from other sites). You’d then want to do your best to fix those links if at all possible.
  • See which pages Google is having trouble crawling. You’d then want to figure out why Google is trying to crawl a non-existent page and set up a redirect if needed.
  • Troubleshoot performance related issues with 404 errors.

Option 1 – Google Analytics

If you use Google Analytics, you can set up a custom report to track 404 errors from external links. Rebelytics has a good tutorial on the topic.

Option 2 – WordPress Plugin

If you want to use a WordPress plugin, the aforementioned Redirection plugin can help you monitor for 404 errors from your WordPress dashboard.

Option 3 – Third-Party Audit Tool

You can also use a third-party audit tool like Ahrefs to monitor for 404 errors on your WordPress site. You can even set this up to run on a schedule.

404 errors audit

404 errors audit

Option 4 – Google Search Console

Lastly, you can track 404 errors that Google’s crawlers encounter in Google Search Console. Once you’ve verified your site with Google Search Console, go to Crawl → Crawl Errors → Not found to view a list of 404 errors that Google has encountered. This is by far one of the easiest ways. It’s also the best in terms of performance because it requires no third-party plugins or additional scanning against your site. Google’s bots are already crawling your site on a regular basis, so why not simply take advantage of the data they already provide? 😉

Google Search Console 404 errors

Google Search Console 404 errors

Summary

Unfortunately, 404 errors will happen on your site whether you like it or not. The larger your WordPress site is, the more you’ll start seeing. We recommend getting a good workflow together for how you monitor these types of errors and go about fixing them. 404 errors are never good for visitors, your brand, and Google doesn’t like to see them either.

Have any other tips or questions regarding the Error 404 Not Found message or how it impacts your WordPress site? Let us know below in the comments.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Technical hygiene of a website means the world when you’re growing traffic volumes, aiming for reaching a better SERP position or turning a profit with advertising. A 404 error cannot turn your SEO and monetization down to zero, however, if search engines detect too many of those, it can be harmful. In today’s post, you will learn what 404 error codes are and how to find and fix them in a most flawless and practical way.  So let’s begin.

Content

  • What is a 404 error?
    • Hard 404 vs. Soft 404 Errors, what’s the difference?
    • What you need to know about your site’s 404 errors
  • Why are 404 errors bad for websites?
  • How to find and fix 404 errors on your site 
    • Tools to find 404 errors
    • How to fix 404 errors
    • Finding and fixing 404 errors on your WordPress site
  • How often should you check for 404 errors?
  • Why should you personalize your 404 page?
  • Conclusion

When a user enters a page’s URL into the browser search bar, the browser identifies the server that houses this page. It then sends the server a request to obtain all the webpage’s files, necessary to display it to the user. When the page is loaded on the user’s device, the HTTP header displays the status code of the server’s response. This user rarely sees this status.

There are 5 types of HTTP response status codes. They indicate how successful a particular HTTP request was:

  • 100–199 Information answers.
  • 200–299 Successful answers. 
  • 300–399 Redirects. 
  • 400–499 Client or Request errors. 
  • 500–599 Server errors.

If the request is correct, and the requested page indeed exists, then a response will be received with the code 200, and the user will be shown the page they requested. But if something went wrong, the error information will appear.
So what is “Error 404?” It is client or request error. The 404 Not Found is a server response code that indicates that the page requested by the user does not exist on the server. The user follows the link to the page, but fails to find the necessary information. They could leave the page unless you make them stay offering helpful content or clues.

Adsterra website page example

Adsterra offers users helpful resources instead of a non-existing page

Hard vs. Soft 404 Errors, what’s the difference?

What does Soft 404 mean? When a Soft 404 error happens, the server sends a “200 OK” status. But Google isn’t satisfied with such an answer. According to Google, the page’s content looks like a 404 error. Usually, pages with Soft 404 errors are non-existent ones or ones that have been deleted but still remain part of the search engine for some time. 

The server’s “200 OK”  answer misleads Google and informs it that there’s a page at this URL address. Search bots end up wasting time scanning and ranking this URL. But Google eventually locates such a page anyway and assigns a Soft 404 Error status to it. And then notifies the publisher through Google Search Console. 

Hard 404 ─ a page that literally can’t be found; it doesn’t exist.

What you need to know about your site’s 404 errors

To identify and fix 404 Not Found errors, you need to know why they happen in the first place. Let’s go over the main reasons.

  1. The user made a mistake and misspelled the page’s address. They may have typed it in manually. 
  2. The user clicked on a dead link. Such links lead nowhere. They appear when pages get internally re-interlinked. In other words, such a page did exist at one point, but was deleted or wasn’t redirected to properly (or at all).
  3. The user tried to access a deleted page. When you delete a webpage from the server, it will remain in the search engine for some time. It’s also possible that the user clicked a link they had saved in their bookmarks.
  4. Very rarely, such an error can occur due to an error on the server’s part.

A “Not-Found” response occurs when it is not possible to find the requested page. It just isn’t on your server. To avoid 404 errors, you need to periodically check the links on your website, find the broken ones and fix them.

Why are 404 errors bad for websites?

You might think that there is little harm in the 404 error. But this is only at first glance. First, you are losing your potential customers. The client follows the link. They want to access your site. But instead, they get a page that tells them the resource does not exist. The not-found pages annoy your customers. They don’t get the information they want and leave your site. Most consumers will think that this website no longer exists. In which case, you lose them forever.

Second, these website responses negatively affect the SEO promotion of your website. 404 errors raise flags for search engines, they don’t like such errors. If, when indexing pages, a search robot encounters a large number of errors, your website’s ranking can take quite a hit. Google sees that your page is not relevant to the user’s request, since the client visited it and then immediately left.

All this means that 404 errors aren’t as harmless as you might think. They damage your website’s rating, not to mention that you lose clients that were willing to buy your product.

How to find and fix 404 error codes on your website

All that begs the question, how do you find and quickly fix 404 errors. The good news is that there are tools to find and manage them with ease. This is especially helpful if your website has a large number of pages. It’s virtually impossible to manually check all your links.

Tools to find 404 error codes

1. Google Search Console

Google Search Console? To see all the 404 error pages on your site, you need to open the Index Coverage Report and click the ERROR tab. Here you can see the key information about your website’s troubles:
Status.
Error type (here you select those containing 404 identifier).
Validation by Google – what’s the current state of the error.

Index coverage report

Another way is to launch an URL checking. The URL Inspection tool is available on the main page of your admin dashboard.

URL inspection tool

And finally, you can get the report by visiting Settings – Stats crawl reports. Here you find the Crawl requests breakdown reports. Choose By Response and pick the “Not found” one.

2. Screaming Frog

To get started with Screaming Frog, you need to download and install the program on your computer. Then, in the window that pops up, enter your website’s URL. The program will display a list of problems.

Screaming Frog tool

2. Ubersuggest

Ubersuggest the SEO tool of renowned marketer and entrepreneur Neil Patel.
Go to the SEO Explorer tab and choose the SEO Analyzer tool. Type in your website URL and wait ~10 minutes until the tool scans your inventory. Then, examine the Critical Errors report.

Ubersuggest tool by Neil Patel

3. Dead Link Checker

Dead Link Checker is a simple and fast web application for finding 404 error pages. You can check both a specific page and the entire site. To start testing, you just need to enter the URL of your website and launch the application. The program will provide you with a list of error pages.

4. Google Analytics

You can also use Google Analytics to track 404 pages. That’s an easy though not very sharp means. From Google Analytics, open “Behavior”, then “Site Content”, then “All Pages”. Click the “Page Title” tab and enter “404” in the search bar. You will get a report containing all pages with 404 title and see how many visitors didn’t found what they were looking for.

How to find 404 errors with Google Analytics

4. MonsterInsights

If you have a WordPress site, install the MonsterInsights plugin. It will automatically track your 404 errors as soon as you open Google Analytics.

MonstersInsights plugin for error checking

How to fix 404 error codes

After locating all your 404 errors, you need to learn to fix them. Let’s take a look at how to fix the most common ones.

1. The link leads nowhere

Such a situation can arise when the page has been assigned the wrong address. How to solve this issue? You need to find the page and attach the correct link to it. This can be done manually if we’re not talking about a lot of pages, or with the help of widgets. They will automatically generate links for pages.

2. The link goes to a deleted page

This problem is connected to pages getting internally re-interlinked. The webpage is long deleted, but the link to it remains. In this case, you can remove the link or direct it to another page. You can automate the process and set up internal linking using third-party programs and services.

Finding and fixing 404 errors on your WordPress site 

How to remove a 404 error on a website created with CMS WordPress.

Fix .HTACCESS

In most cases, the problem lies in a missing .htaccess file. You need to create an empty text file with the “.htaccess” extension in the website’s root folder. Then, add standard WordPress directives to it.

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Fix your permalink structure

  • Log in to your WordPress Admin panel.
  • In the left menu click “Settings.”
  • Go to “Permalinks.”
  • If you are using a custom permalink structure, copy and save them in any text editor.
  • Select the default value.
  • Click “Save settings.”
  • Change the settings back to what they previously were (before selecting Default). 
  • Return the custom structure if you had one.
  • Click “Save settings.”

how to fix permalinks in WordPress

Set up redirects for pages with changed URLs

Setting up WordPress redirects allows search engines to index websites’ new URLs while deleting old ones.

But only certain HTTP redirect codes will let you maintain your search engine rankings. You can read more about these redirection codes in this article.

set up redirects to fix 404 error codes

How often should you check for 404 error codes to fix them?

Check your website for 404 errors each month if you have a small website (around 50 pages). If the number of pages exceeds 50, then you should perform this little “check-up” every week. Checking for technical pitfalls won’t eat up too much time, but it will save customers, as well as preserve the website’s search engine rating.

Why personalize your 404 error page?

Clicking on a broken link is always annoying – on the other side only broken dreams and irritation await the user. And worst of all – that may have been your potential buyer, who could’ve turned into a loyal and regular customer.

No matter how hard you try, from time to time your users will get the 404 error message. You are very unlikely to get rid of this issue altogether. But are there perhaps ways to sugar-cover the bitter truth?

If the problem cannot be avoided, then we must try to turn it into a useful tool that will convert such mistakes into buyers. How?

  1. Retain the user’s attention on a non-standard situation.
  2. Present the error as an annoying misunderstanding.
  3. Say that the good news is that the required information is probably on the website.
  4. Offer simple and understandable alternatives.

The most important thing is to reject the faceless standard 404 error page that does nothing but state the irritating fact, leaving the client with no other choice but to just close the page.
Don’t disappoint your customers. Create your own unique personalized page. In accordance with the recommendations of search engines, the 404 page should fit into the overall concept of the website’s design. It should be a continuation and addition of it.

Things you can place on the 404 error page

Popular CMSs make it possible to add various website elements on the 404 pages:

  • home page links;
  • links to the website’s best content;
  • sitemaps;
  • search forms;
  • feedback forms;
  • catalog categories;
  • lead generation or subscription forms.

Why you need a unique 404 page for your website

First of all, to retain a potential client, help them find the info they’re looking for, strengthen the brand, calm the user’s irritation, add a little humor to the situation, etc.
Here are some good examples of 404 pages used by popular brands.

Disney

Disney 404 page

An engaging 404 page by Disney

Amazon

Amazon Not-Found page

Dogs of Amazon are waiting on the Error pages

Magento

Magento offers its top categories on 404 pages

Conclusion

To end off this article in a more practical manner, with a few more tips:

  • Avoid using long and complicated page titles.
  • Keep URLs unchanged. Try not changing URLs too often as it confuses the user, search bots and you as well.
  • Choose reliable hosting services. By doing so you’ll save yourself a lot of trouble.

404 errors are inevitable. Use these recommendations and tools, conduct regular checks to find and fix these errors, and they won’t get the chance to do any damage.

Improving a website is an ongoing mission, but you can start earning on traffic any moment. Adsterra is known for the fastest website approval and high payouts for publishers. Join the community of passionate pros!

I’m new to Yii2,

here is the website almousa.net
the issue here that I can not go to the backend, I always get The requested page does not exist and the page title Not Found (#404)

I tried everything from changing the .htaccess to changing the url
how can I solve that?
I noticed that there are no index.php in the website base folder and as if all the requests are going to the front end
website base folder

asked Jan 12, 2018 at 0:23

Iyad Bacdounes's user avatar

5

Even I have installed a fresh copy of Yii2 advanced and following standard steps I got everything OK. But the same problem like you mentioned here that the backend was not working.For this I added an additional .htaccess file inside backend folder(/backend) with the following code:

Options -Indexes
<IfModule mod_rewrite.c> 
RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ web/$1 [L]
</IfModule>
# Deny accessing below extensions
<Files ~ "(.json|.lock|.git)">
Order allow,deny
Deny from all
</Files>
# Deny accessing dot files
RewriteRule (^.|/.) - [F]

Please do follow and I hope it helps.Your config settings must be correct in addition to 1 more .htaccess inside backend/web folder with the following code:

    RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php

answered Jan 12, 2018 at 7:55

Ravi Singh's user avatar

3

Ошибка 404 (Error 404 Not Found с англ. «не найдено») — это ошибка сервера, обозначающая отсутствие запрошенной для отображения страницы на сервере, простыми словами, это удаленная или недоступная в настоящий момент страница сайта.

Почему возникает ошибка 404

Код ошибки 404 означает, что клиент успешно обменялся данными с сервером, однако необходимые данные так и не были обнаружены. Самая частая причина 404 ошибки — элементарное удаление страницы.

Допустим:

  • На сайте существовала страница с адресом tooth.com/new-born.
  • Через некоторое время она была удалена вебмастером.
  • Теперь при попытке открыть страницу tooth.com/new-born пользователь увидит сообщение «Страница не найдена». Или другие, более интересные варианты.

Cтраница может быть красивой и функциональной

Cтраница может быть красивой и функциональной

Это самый частый случай появления 404 ошибки на сайте. Но не единственный. Вот некоторые другие сценарии:

  • Ошибка при ручном вводе URL. Если пользователь вручную набирает адрес страницы, вероятность допустить ошибку очень велика. Например: facebok.com, вместо facebook.com
  • Некорректное перенаправление. Для ускорения оптимизации сайта часто проводятся однотипные операции сразу с большим количеством страниц. В процессе таких изменений могут меняться названия и адреса веб-страниц, настраиваться некорректные перенаправления. Если автоматически измененных страниц очень много, то и уследить за корректностью всех редиректов может быть сложно. Например: настраивается глобальный редирект всего домена с HTTP на HTTPS.
  • Сбой сервера. Этот вариант разумно проверять в последнюю очередь, так как он встречается нечасто. Самые распространенные причины сбоя сервера: физическое отключение, потеря сети, конфигурационный сбой.

Как проверить ответ страницы

Откройте инструмент «Проверка ответа сервера» в «Яндекс.Вебмастере», укажите опрашиваемый URL и тип робота (для которого будет проверяться на ответ сервера):

При необходимости укажите дату для проверки заголовка HTTP запроса If-Modified-Since

При необходимости укажите дату для проверки заголовка HTTP запроса If-Modified-Since

После нажмите кнопку «Проверить». Вы сразу увидите ответ, который отдает сервер по выбранному URL.

Для проверки ответа сервера (HTTP status code,или ответ сервера, который предусмотрен при использовании HTTP-запросов) также удобно использовать Checkmy. Принцип такой же, как и в «Яндекс.Вебмастере». Открываем сервис и указываем URL страницы, которую нужно проверить. Нажимаем кнопку «Отправить запрос» внизу страницы:

Опционально выбираем User Agent и устанавливаем дату для проверки заголовка HTTP запроса If-Modified-Since

Опционально выбираем User Agent и устанавливаем дату для проверки заголовка HTTP запроса If-Modified-Since

Страница отдает 200-й код, что говорит о том, что она доступна пользователю:

Результат проверки ответа сервера

Результат проверки ответа сервера

Что будет, если на сайте много ошибок 404 not found

Ничего хорошего точно не будет. Для пользователя несуществующая страница не представляет никаких проблем. Он просто откроет поиск и перейдет на другой попавшийся сайт.

Каким бы способом пользователь ни открывал удаленную ссылку (через закладки браузера, прямой ввод URL, переход по ссылкам) исход всегда одинаковый — открывается страница 404.

Гораздо неприятнее ошибка 404 для вебмастера. Вот ее основные опасности:

  • Технические ошибки. Большое количество битых ссылок может привести к техническим проблемам на сайте и затруднению индексации ПС.
  • Исключение из индекса. Ненайденная страница очень быстро покидает индекс. Если у такой страницы были хорошие позиции, по личному опыту скажу, что набрать их повторно может быть очень сложно. Доступны рекомендации по работе с 404 страницей от «Яндекса» и Google.

Как исправить ошибку 404 пользователю

Посетитель не может повлиять на 404-ю ошибку прямым образом. Но может сделать это косвенно:

  1. Связаться с вебмастером сайта. Необходимо сообщить вебмастеру о найденной битой ссылке.

    Пример страницы ошибки, которая позволяет связаться с поддержкой сайта

    Пример страницы ошибки, которая позволяет связаться с поддержкой сайта
  2. Ждать. Если страница была действительно ценной, вебмастер рано или поздно восстановит ее. Возможно, что он просто не успел настроить перенаправление или добавить обновленную версию контента, временно удалив старую версию страницы. Попробуйте обновить удаленную страницу через несколько дней.

    Подождите 1-2 дня и нажмите F5, чтобы обновить страницу

    Подождите 1-2 дня и нажмите F5, чтобы обновить страницу
  3. Проверить интернет и подключение на своей стороне. В некоторых случаях ошибка 404 появляется из-за проблем с подключением на стороне пользователя. Чтобы подтвердить этот сценарий, откройте любую другую страницу в интернете. Если она не открылась — это как раз ваш случай. Убедитесь, что сетевое оборудование настроено корректно и выход в интернет имеется на вашем устройстве:

    Выход в интернет активен

    Выход в интернет активен

Как исправить ошибку 404 вебмастеру

Теперь дадим рекомендации для вебмастеров.

Во-первых, необходимо регулярно мониторить битые ссылки на своем сайте. Для выполнения этой задачи вы можете использовать Google Search Conslie и «Яндекс.Вебмастер».

Чтобы найти все удаленные 404 страницы из поиска Google, откройте GSC и перейдите в отчет «Покрытие»:

Находим 404-е страницы на своем сайте при помощи Google Search Conslie

Находим ошибку 404 на своем сайте при помощи Google Search Conslie

В «Яндекс.Вебмастере» есть аналогичный отчет. Чтобы получить к нему доступ, откройте пункт «Индексирование»:

Открываем отчет по страницам в поиске в «Яндекс.Вебмастере»

Открываем отчет по страницам в поиске в «Яндекс.Вебмастере»

Теперь кликаем по кнопке «Исключенные» в верхней части экрана и чуть ниже отмечаем одноименный фильтр

Находим исключенные страницы на своем сайте

Находим исключенные страницы на своем сайте

Во-вторых: что делать дальше? После того как битая страница найдена — можно приступать к ее «ремонту». Алгоритм действий такой:

  1. Еще раз проверьте корректность URL.
  2. Восстановите или добавьте новый контент на страницу с битым адресом.
  3. Опубликуйте страницу.
  4. Альтернативное решение — удалить страницу с битой ссылкой и дождаться, пока ПС ее исключат из поискового индекса.

Можно также изменить адрес страницы, чтобы он стал работающим и приводил к открытию существующей страницы. Или еще проще: вместо удаленной страницы good.ru/blog/google-said создать новую страницу с адресом good.ru/blog/google-said-new, например.

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

Как улучшить страницу ошибки 404

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

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

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

Но 404-я страница совсем не обязательно должна быть серой и безвкусной. И вот тому доказательство:

Piratecode подошел к созданию с долей иронии

Piratecode подошел к созданию с долей иронии

Что можно сделать с этим? Попробуйте настроить внешнее и функциональное воплощение несуществующей страницы сайта.

Вот еще примеры, как можно улучшить страницу 404 ошибки функционально:

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

    C двумя ссылками

    C двумя ссылками
  2. Опубликуйте форму поиска по сайту.

    C поисковой строкой

    C поисковой строкой
  3. Разместите e-mail технического специалиста/вебмастера или техслужбы сайта, чтобы пользователь мог написать туда при нахождении битых ссылок:

    C кнопкой «Сообщить об ошибке

    C кнопкой «Сообщить об ошибке
  4. Опубликуйте кнопку главной страницы. Возможность вернуться на главную страницу снизит процент отказов.

    C URL на главную

    C URL на главную
  5. Разместите виджет с популярными вопросами или популярными страницами:

    C несколькими ссылками

    C несколькими ссылками

Понравилась статья? Поделить с друзьями:
  • Error 404 the file you requested could not be found
  • Error 404 tale
  • Error 404 svg
  • Error 404 song
  • Error 404 site