Joomla выдает 404 ошибка

The most common problem with websites which are struggling in search engine rankings is the number of ‘not found’ errors – commonly referred to as 404 errors because that is the status code returned if the page cannot be found.

First, there are legitimate reasons to have 404 errors – if you have a page for an event which has passed, or a service which you no longer provide. In these cases, eventually the page will be removed from the index of search engines and won’t be associated with your site any more.

The problem occurs if you have a lot of 404 errors – for example if you unpublish a category which contained hundreds of articles. From the search engine’s perspective, this is not a great experience for their visitors, because they land on your site and the information that the search engine told them was there, isn’t. This is why it is not a great idea to have too many 404 errors on your site.

The first step is to find out how many you have – which can be done using Google’s Search Central. This is a free set of tools which allows you to analyse your website and pick up on problems, errors and issues quickly. It is recommended that you have every site you manage registered at Search Central to ensure you are notified in the event of any problems.

When you visit Search Central there is a section which shows you URL Errors in the search listing – this will show you a list of the 404 errors that Google has found on your site, and a graph which shows you how this has changed over time. If the graph starts to go up, look into why there are pages that were on your site and now can’t be found.

If there was a temporary problem on your site, you can mark errors as being fixed.

404discovery.png

Fixing Problems[edit]

Discovery is only one part of the process. Once you have discovered the problematic URLs, do something about it (if it needs fixing!) by either redirecting the page to another on the site, re-instating the original page, or looking into what has caused the 404 error.

If you need to redirect a page, check out this page which explains how to create 301 (permanent) redirects: Creating 301 redirects

Monitoring Problems[edit]

If you want to monitor your 404 traffic, the best way to do this in Analytics is to look at what happens when you have a 404 error. In most cases, the page title changes to 404 – so we can create a custom segment which will filter traffic with a title of 404 and tell you what the landing page is. This should allow you to monitor and proactively manage your 404 errors and ensure that your site visitors do not end up landing on dead links.

Analyticsalerts.png

Analyticsalerts2.png

Google also has the ability, in Analytics, to set up alerts. Alerts allow you to be emailed when certain events occur. In this case, we can set up an alert to be notified if there is more than a 5% increase in the number of 404 errors in a weekly period – which might mean we have a problem with the website which needs investigating.

This is a great way to keep on top of things even if you haven’t logged in to look at your dashboard!

Analyticsalertsemail.png

Monitoring Errors with a Dashboard[edit]

There is also a dashboard you can install called the Data Integrity Dashboard which shows you information about 404 errors, along with some other metrics which might be of interest. Just search the Google Analytics Gallery for Data Integrity Dashboard and select which profile to install it under.

Dataintegrity.png

Узнайте, как правильно создать и настроить собственную страницу ошибки 404 для сайта на Joomla 3 и Joomla 4, отображаемую в интерфейсе шаблона.

Важно знать!

Ошибка 404 (Error 404) — это ответ сервера, отправляемый при запросах на несуществующие ресурсы.

Веб-сервер должен отправлять ответ 404 Not Found в случае, если соответствующего запрашиваемому URL-адресу ресурса не существует.

Что такое страница ошибки 404?

Важно знать!

Страница ошибки 404 — это веб-страница, отображаемая при прямом запросе на несуществующий документ.

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

Страница ошибки 404 в шаблонах Joomla

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

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

Создание страницы 404 в интерфейсе шаблона

Разберем по пунктам, как правильно создать и настроить собственную страницу ошибки 404 в теле стандартного шаблона Protostar для Joomla 3 с отображением контента в области компонента.

Важно знать!

Указанная инструкция актуальна как для Joomla 3, так и для Joomla 4.

  1. Создать и опубликовать материал, который будет отображаться при запросе несуществующей страницы. Примеры опций:
    • Заголовок: «Страница не найдена».
    • Алиас: «error-404».
    • Cодержание: «Указанной страницы не существует. Вероятно, она была удалена или перенесена на другой адрес.»
    • Категория: «Uncategorised».
  2. Создать и опубликовать скрытый пункт меню данного материала с алиасом error-404:
    • Во вкладке Параметры материала необходимо отключить показ всей лишней информации (Автор, Хиты, Дата публикации и т. д.).
    • Во вкладке Параметры ссылки необходимо установить опцию Показать в меню на Нет, чтобы скрыть пункт меню.
    • Во вкладке Параметры страницы можно прописать тег <title>, который будет отображаться вместо названия материала. Например: «Ошибка 404 — страница не найдена».
    • Во вкладке Метаданные выбрать значение метатега Robots noindex, nofollow.
  3. В папке шаблона (/templates/шаблон) создать или заменить существующий файл error.php, который должен содержать только следующий код:
    <?php
    defined( '_JEXEC' ) or die( 'Restricted access' );
    if($this->error->getCode() == '404'){
        header("HTTP/1.1 404 Not Found");
        echo file_get_contents(JURI::root().'error-404');
        exit;
    }
  4. Проверяем функционирование страницы. По запросу несуществующего документа должен отображаться созданный материал.
  5. Проверяем ответ сервера для несуществующей страницы. Для этого можно воспользоваться панелью разработчика в браузере или сторонним веб-сервисом.
  6. Чтобы сделать страницу ошибки 404 более наглядной, рекомендуем добавить в её контент соответствующее изображение, которое без труда можно найти в поисковой выдаче картинок, а также отключить на ней ненужные модули.

Видеоинструкция

Время на прочтение
2 мин

Количество просмотров 14K

image

Известно, что для того, чтобы удержать посетителя на сайте, нужно правильно обрабатывать HTTP/1.0 404 и другие подобные коды. На просторах интернета можно найти массу занимательных примеров страниц 404, а также руководств – что и как сделать, чтобы ошибка 404 правильно обрабатывалась сайтом как для посетителя, так и для поисковых систем.

Хочу с вами обсудить проблему 404 для сайтов Joomla.

Общие рекомендации по настройке Joomla для обработки HTTP/1.0 404

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

  1. Создаем в нашей Joomla «красивую страничку 404». Можно несколько — при реализации вашей особенной логики и способа их выбора для
    посетителя;
  2. В свой шаблон, который используется на сайте в качестве основного шаблона frontend, из системного шаблона system переписываем файл error.php;
  3. Далее редактируем этот файл для того, чтобы следовать следующей логике – если мы отловили ошибку 404 – то сначала выдать заголовок HTTP/1.0 404, а затем выдать страницу, которую мы ранее подготовили. Предположим, номер (ID) нашей «красивой страницы 404» равен 1001. Файл error.php в вашем шаблоне может выглядеть так:

defined('_JEXEC') or die;

if (!isset($this->error))
{
	$this->error = JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
	$this->debug = false;
}

// Get language and direction
$doc             = JFactory::getDocument();
$app             = JFactory::getApplication();
$this->language  = $doc->language;
$this->direction = $doc->direction;

if($this->error->getCode()=='404') {
	header("HTTP/1.0 404 Not Found");
	header('Location: index.php?option=com_content&view=article&id=1001');
}

Теперь проверяем. Вводим адрес сайта. Далее – абракадабра после символа /. Работает? Работает, чего и следовало ожидать.

В чем подвох?

Открываем отладку страниц в вашем любимом браузере (мой любимый браузер – Fitefox с Firebug-ом), вкладка «Сеть», и смотрим заголовки, которыми общается браузер с сайтом.

Вводим адрес сайта – заголовок HTTP/1.0 200 OK

Теперь абракадабра… Ожидаем HTTP/1.0 400 Not Found — смотрим заголовки:

  1. Сначала HTTP/1.0 302 Found
  2. Затем наша красивая страница отдается браузеру с кодом HTTP/1.0 200 OK

image

Чем это плохо?

— Но, ведь, работает? — Скажете вы. Да, работает. А как на это смотрит поисковая система?

Был у меня переезд страниц сайта с одного раздела (папки) сайта на другой. Но переехать должны были не все страницы. Страницы старого раздела сайта были в индексе. Те, что переехали – выдавались с кодом HTTP/1.0 301 Moved Permanently (классика жанра) и поисковики их правильно «переехали» на новое место. А те, что должны были «кануть в лету» – так и мелькали в индексе, хотя физически отсутствовали на сайте, а при обращении к ним выдавалась «красивая страничка 404», но не код HTTP/1.0 404 (смотрим выше).

Выход из этой ситуации

Для страниц с ошибкой 404 я решил выдавать заголовок HTTP/1.0 404 Not Found и делать не редирект через заголовок Location, а читать поток «красивой страницы 404» и перенаправлять его браузеру. Вот реализация:

if($this->error->getCode()=='404') {
	header("HTTP/1.0 404 Not Found");
	$url=JURI::root()."index.php?option=com_content&view=article&id=1001";
	$data = file_get_contents($url) or die("Cannot open URL");
    echo $data; 
}

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

When you get a 404 error on your Joomla website, there are a few things you can do to fix it.

The most common cause of a 404 error is a missing file. Make sure you have all the files you need in your website folder and check that the file is actually there. If the file is there, make sure you have the correct file name and version.

If the file is not there, you may have a problem with your website’s configuration. Check to see if you have the correct permissions for your files and folders, and make sure the files are actually being served.

If all of that fails,

If you are receiving a 404 error when trying to access your Joomla site, the page you are trying to reach does not exist. There are a few ways to fix this error:

1. Check the URL you are trying to access. If you are sure that the URL is correct, try reaccessing the page.

2. If the URL is correct but you are still receiving a 404 error, it may be due to a problem with the server. Contact your hosting provider to troubleshoot the issue.

3. If the URL is incorrect, you can try to find the page you are looking for by using the search function on the Joomla site.

4. If you can still not find the page you are looking for, you can create a new page with the correct URL.

Let’s See: How to Change Joomla Database Prefix in Joomla 4?

How do I get rid of Error Code 404?

If you’re seeing a 404 error code when you try to visit a website. It means that the page you’re looking for can’t be found. There could be a few different reasons for this:

The page may have been moved or deleted.
The page may have been renamed.
You may have mistyped the URL.

If you’re sure you’ve got the URL right, the first thing to do is check with the website to see if they can help you find the page you’re looking for. If not, there are a few other things you can try:

Check your browser’s history to see if you can find the page there.
Search for the page on a search engine.
Try to find the page on the website’s sitemap.

Still can’t find what you’re looking for? Contact the website’s customer support to see if they can help you out.

Let See: How to update Joomla to the latest version

how do you make Joomla return a «real» 404 code? I can’t figure out how to make this happen! I have changed htaccess.txt to .htaccess, enabled the system / redirect plugin, and turned on rewrite URLs in the the Joomla global options.

However, any fake URL I type in simply redirects to the homepage, not even to the default Joomla error page.

This also happens even on the Joomla demo site here:
https://demo.joomla.org/badurl_fake

Testing further:

Joomla Global Use Rewrite: OFF
Joomla htaccess.txt renamed: NO
Joomla redirect plugin enabled: NO

This results in a bad URL returning a true 404 error

Joomla Global Use Rewrite: ON
Joomla htaccess.txt renamed: NO
Joomla redirect plugin enabled: NO

This results in a bad URL returning a true 404 error

Joomla Global Use Rewrite: ON
Joomla htaccess.txt renamed: NO
Joomla redirect plugin enabled: YES

This results in a bad URL returning a true 404 error

Joomla Global Use Rewrite: ON
Joomla htaccess.txt renamed: YES
Joomla redirect plugin enabled: YES

This results in a bad URL returning user to homepage

Joomla Global Use Rewrite: OFF
Joomla htaccess.txt renamed: YES
Joomla redirect plugin enabled: YES

This results in a bad URL returning user to homepage

Joomla Global Use Rewrite: OFF
Joomla htaccess.txt renamed: YES
Joomla redirect plugin enabled: NO

This results in a bad URL returning user to homepage

So it seems to me that the htaccess is the culprit here. In my testing, anytime the .htacess is present, the 404 is redirected to the index page.

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Jlr sdd как сбросить ошибки
  • Jino ошибка 403 доступ запрещен
  • Jinn2usb ошибка определения дисков как исправить
  • Jinn client ошибка создания com объекта модуль 50
  • Jetta ошибка esc

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии