Ошибка 301 http как исправить

Здравствуйте, уважаемые друзья и гости блога! Сегодня пойдет речь о такой странной вещи на сайте, как ошибка 301 Moved Permanently (переехал навсегда) или по другому редирект 301.

Думаю. что все с таким сталкивались, а некоторые даже использовали данную “ошибку 301” на своих сайтах. Но не все знают для чего эта ошибка 301 или иначе редирект 301 нужна на сайте? Для чего он, 301 редирект, используется?!

Вот сейчас мы с вами и займемся разбором этого вопроса во всех его подробностях и нюансах …

Как Вы уже наверное догадались по переводу слов “moved permanently” – это дословно, что сайт или отдельная его страница “переехал навсегда” по адресу на который Вас перекинул ваш браузер. Тут надеюсь все понятно и ясно без лишних пояснений!

Но возникает вопрос. Для чего это сделано вебмастером этого сайта? Почему он поставил редирект 301 и у нас с вами выскакивает иногда 301 ошибка? А все просто! Ошибка 301 появляется, когда сервер перебрасывает нас с уже не работающего сайта на страницу сделанную специально для перенаправления пользователя на рабочий сайт, но просто с некоторой задержкой или вообще на этой странице нужно самостоятельно перейти по ссылке. Вот это в двух словах об ошибке 301.

Теперь самый важный момент, зачем же все таки нужен редирект 301 на сайте …

Редирект 301 и для чего он нужен?

Есть несколько причин у вебмастера, чтобы использовать редирект 301. Вот они:

  • Причина первая: Склейка домена с www и без www. При этом все seo показатели сайта и его ссылочный вес будут совмещены и не будут отличаться друг от друга.
  • Причина вторая: Если вдруг пришлось сменить домен для сайта. Тогда применяется редирект 301 и он как раз перенаправляет посетителя сайта и поисковые роботы на рабочий домен сайта. Это также позволит вам сохранить все seo показатели вашего переехавшего сайта, как тИЦ, PR, так и своих посетителей.
  • Причина третья: Использование редиректа 301 при переносе отдельной страницы сайта на другой ресурс. Бывают и такие случаи, когда это нужно сделать.
  • Причина четвертая: Например у Вас есть сайт, где высокий тИЦ и PR и много посетителей. И еще есть другой сайт, который нужно немного пропиарить и прибавить к нему посещения. Тогда Вы просто на просто перенаправляете при помощи того же редирект 301, с одной страницы высоко посещаемого сайта на страницу более низко посещаемого сайта и тем самым выигрываете, добавив ему веса ссылочной массы и соответственно посещений.

Вот основные причины для использования редирект 301 или ошибка 301 Moved Permanently.

Теперь давайте узнаем, как правильно использовать редирект 301 на своем сайте и как настроить его через файл htaccess …

301 редирект и файл htaccess – как правильно настроить?

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

Для чего это нужно мы с вами также уже разобрали. Но как же это сделать правильно на нашем сайте используя файл htaccess? Сейчас я вам все подробно объясню и приведу примеры внесения изменений в файл htaccess для вашего сайта!

  • Перенаправление домена с www на без-www
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

или вот более понятный синтаксис:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]
  •  301 редирект запросов без-www на домен с www префиксом
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]

Альтернативный вариант:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.(.*) [NC]
RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]
  •  301 редирект старого домена на новый в фале htaccess
Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]
  •  Если вам нужно, чтобы вместо rewrite.htm загружался файл rewrite.html, добавьте в файл htaccess вот это:
RewriteEngine   on
RewriteBase     /
RewriteRule     ^rewrite.htm$  rewrite.html [R=permanent]
  •  Чтобы заменить все .htm файлы на .html внесите в файл htaccess:
RewriteEngine  on
RewriteBase     /
RewriteRule     ^(.*).htm$  $1.html [R=permanent]
  •  Варианты, когда не нужно использовать 301 редирект на вашем сайте:
  • Если реализация 301 редиректа невозможна или она займет неоправданно много времени.
  • Если контент вашего сайта дублируется на двух или нескольких страницах, но эти страницы должны быть доступны в поиске пользователю ввиду некоторых отличий (на пример, выбор какого-то товара).
  • Если одна страница имеет несколько URL адресов (сортировка каталога товаров по различным категориям или критериям).
  • Для кросс-доменов. Это, когда контент сайта на двух URL адресах дублируется, но он должен быть доступен на каждом из двух или нескольких доменах.

Этот материал посвящен выходу 301-ой статьи на моем блоге!

Может вам интересно узнать, что такое ошибка 503 и как ее устранить?

На этом пока все. Всем удачи и благополучия!

При работе с веб-ресурсами возникают ситуации, когда происходит удаление, перенос или изменение url-адреса отдельных страниц или сайта целиком. При этом требуется сохранить индексацию в поисковых системах и перенаправить пользовательский трафик на новый адрес. Для решения этой задачи используется функция под названием 301 Redirect. Это один из инструментов SEO, который позволяет не только избежать ошибок при открытии отдельных страниц, но и добиться корректной работы ресурса. Правильные настройки редиректа дают дополнительную возможность получить синергетический эффект в поисковой оптимизации и увеличить количество органического трафика на релевантные страницы. Рассмотрим более подробно, как происходит настройка редиректа 301.

Что такое переадресация 301

Permanent Redirect 301 применяется с целью организации постоянной переадресации с неактуального доменного адреса или url отдельной страницы на рабочую версию. Редирект может понадобиться в связи с глобальным переносом сайта на другой домен, техническими изменениями в написании адреса, удалением страниц, необходимостью внутренней и внешней перелинковки. Один из вариантов использования перманентной переадресации – редирект с нескольких доменных имен, созданных в разных зонах, на один актуальный адрес. Грамотное использование редиректа позволяет перемещать контент без потерь в поисковой индексации, сохранить и даже увеличить прежний вес и позицию в выдаче.

Настроить код состояния HTTP 301 можно разными способами:

  • с помощью HTML и PHP;

  • через панель управления или плагины соответствующей CMS;

  • при помощи специальных скриптов (программ);

  • на уровне хостинг-провайдера;

  • внесением соответствующих записей в файлы .htaccess для сервера Apache или web.config для IIS.

Последний способ является наиболее простым и надежным. О нем чуть позже поговорим подробнее.

Редирект

Альтернативные методы переадресации

  • Редирект 302. Применяется в случае временной переадресации с одного url на другой. При его использовании поисковая система индексирует все доступные версии сайта или страницы. Объединения ссылочного веса и внутренних метрик на приоритетном ресурсе не происходит. 
  • 307 Temporary Redirect рекомендуется применять в исключительных случаях. Например, при техническом обслуживании сайта, когда он недоступен некоторое время. 
  • Обновления Meta Refresh выполняют переадресацию не на уровне сервера, а непосредственно на сайте. Пользователь сталкивается с временной задержкой (обычно около пяти секунд), после чего для перехода на нужную страницу должен принудительно запустить определенную команду. Этот метод часто приводит к падению посетительского интереса и проседанию поисковых индексов.
  • Редирект rel=«canonical». Позволяет сохранить доступ посетителям ресурса к контенту дублирующихся страниц. При этом для поисковиков наличие команды canonical на одной из страниц говорит о том, что только она подлежит индексации в поиске.

В большинстве случаев постоянная переадресация является более правильным решением, чем временная. На практике это объясняется просто. Предположим, сайт сменил доменную зону, а затем еще и обзавелся защищенным протоколом https. При настройке временной переадресации в индексе Яндекса и Google по одним и тем же запросам появились три версии сайта с пропорциональным проседанием позиций в выдаче. После настройки редиректа 301 на приоритетный url произошло склеивание дублей, робот вернул сайт в топ выдачи. 

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

Редирект 301

В каких случаях используется постоянный редирект 301

  1. Смена доменного имени, перенос сайта. Необходимо произвести тотальную настройку переадресации со старого адреса на новый, чтобы все без исключения запросы к old_site.ru перенаправлялись на new_site.ru.

  2. Изменение написания url определенных страниц в целях SEO-продвижения, смены CMS или по иным причинам. Требуется настроить редирект с site.ru/1hdkr5 на site.ru/page_adress.

  3. Перенос разделов на субдомены. Необходимо сменить адрес www.site.ru/example на example.site.ru.

  4. Для аккумуляции трафика с адресов, купленных в разных доменных зонах, на один приоритетный ресурс. 

  5. Исключение дублирующихся страниц из индекса. 

  6. Склейка зеркал сайта – вариантов сайта с идентичным контентом, но разным написанием адресов: site.ru, www.site.ru, https://site1.ru и т.д. В этом случае выбирается один приоритетный домен и на него настраивается редирект со всех остальных зеркал.

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

  8. Для быстрого перехода пользователя на мобильную версию ресурса со смартфонов и планшетных устройств.

Создание постоянной переадресации 301 через настройки и плагины CMS

В большинстве популярных конструкторов сайтов и CMS (OpenCart, Joomla!, Битрикс, Wix, Тильда) предусмотрена настройка редиректов с помощью встроенных инструментов. Если сайт создан с помощью WordPress, для настройки переадресации можно воспользоваться следующими плагинами:

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

  • Safe Redirect Manager — простой плагин, который также поддерживает регулярные выражения, практически не влияет на производительность сайта.

  • Quick Page/Post Redirect Plugin — еще один удобный инструмент оптимизации. Один из недостатков — отсутствие поддержки регулярных выражений. К ссылкам можно добавлять атрибут «nofollow».

  • Simple 301 Redirects. Данный модуль обладает одним недостатком – url для переадресации необходимо прописывать вручную.

Настроить Permanent Redirect 301 в Вордпресс можно и через редактирование файла .htaccess в разделе управления хостингом. Чтобы подключиться к нему, потребуется использовать FTP-клиент. Сама кодировка производится по общим правилам настройки переадресации в .htaccess.

Чтобы настроить 301 редирект в CMS OpenCart в файле .htaccess необходимо прописать:

RewriteCond %{QUERY_STRING} ^_route_=адрес_старой_страницы.html$

RewriteRule ^(.*)$ http://ваш_домен.ru/новой_страницы/? [R=301,L]

Для Битрикс кодировка будет выглядеть следующим образом:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www.sng-it.ru$ [NC]

RewriteRule ^(.*)$ http://sng-it.ru/$1 [R=301,L]

В Joomla настройки переадресации производятся через панель администратора в разделе «Компоненты» => «Перенаправление». Здесь можно не только установить правила редиректа, но и отслеживать страницы с битыми ссылками и перенаправлять их на корректные адреса.

.htaccess

С конструкторами сайтов все не так однозначно. Например, один из наиболее популярных CMS-конструкторов WIX не предоставляет возможности создания файла .htaccess.

Настройка htaccess

Но настроить редирект 301 довольно просто в базовом редакторе.

Настройка 301 редирект в .htaccess

Файл с расширением .htaccess – это дополнительный конфигурационный файл web-сервера Apache. Его используют для настройки веб-сервера, а также для обработки различных URL-адресов.

Для настройки 301 редиректа в файле .htaccess чаще всего применяют одну из трех директив: Redirect, RedirectMatch или RewriteRule. Директивы относятся только к папке, где размещен .htaccess, а оттуда распространяются на дочерние папки.

Найти файл можно через панель управления хостинга либо использовать FTP-клиент. При любом варианте нужно включить отображение скрытых файлов.

Предварительная подготовка

  • Для создания 301 редиректа перейдите в панель управления вашего сайта.

  • Проверьте наличие .htaccess файла в корневом каталоге сайта (public_html, если используете WordPress). Если файл отсутствует, создайте его.

  • Рекомендуем все условия редирект записывать в блоке IfModule, дабы избежать ошибок при выполнении файла htaccess.

<IfModule mod_rewrite.c>
</IfModule>
  • Перед тем как начать прописывать правила перенаправления, необходимо включить механизм преобразований (RewriteEngine) при помощи команды RewriteEngine On.

  • Хостинги применяют по умолчанию 302 или любой другой 3xx редирект. В связи с этим в правилах используются флаги. Рекомендуем дописывать в своих правилах [R=301,L].

Разберем наиболее распространенные варианты создания 301 редиректа через .htaccess.

Склейка зеркал сайта (www / без www)

Сайты http://name.site и http://www.name.site для поисковых систем являются разными. А по факту это разные адреса одного сайта.

В поисковой системе сайт по одному адресу будет проиндексирован, а по второму адресу зафиксирован как дубль, что может повлиять на продвижение ресурса. Для избегания дублей необходимо сделать так называемую «склейку» сайта, то есть прописать 301 редирект в .htaccess.

Если изначально в индекс поисковой системы попала версия «с www», в файл .htaccess добавляется редирект на «без www»:

RewriteCond %{HTTP_HOST} ^www.name.site$ [NC]

RewriteRule ^(.*)$ http://name.site/$1 [R=301,L]

Если произошла обратная ситуация и необходима переадресация с без «www» на «www», то в файл прописывается:

RewriteCond %{HTTP_HOST} ^v name.site$ [NC]

RewriteRule ^(.*)$ http://www.name.site/$1 [R=301,L]

Редирект с http на https для всего сайта

В случае перехода на защищенный протокол https для всего сайта, необходимо настроить перенаправление с http на https. Для этого в файл .htaccess добавьте:

RewriteCond %{SERVER_PORT} !^443$

RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

Если данная конструкция не сработает, попробуйте другой вариант:

RewriteCond %{HTTPS} =on

RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L]

RewriteCond %{HTTPS} off

RewriteCond %{HTTP:X-Forwarded-Proto} !https

RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Если редирект не работает и в этом случае, попробуйте такой вариант:

RewriteEngine On

RewriteCond %{SERVER_PORT} !^443$

RewriteCond %{REQUEST_URI} =/page.php

RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

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

Постранично

Бывают случаи, когда необходимо создать редирект на https всех страниц, кроме одной. В этом случае используют постраничный редирект:

RewriteEngine On

RewriteCond %{HTTPS} =off

RewriteCond %{REQUEST_URI} !^/page.php

RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L]

Для одной страницы

Для редиректа с http на https одной страницы (например page.php), в файл добавьте следующую конструкцию:

RewriteEngine On

RewriteCond %{HTTPS} =off

RewriteCond %{REQUEST_URI} =/page.php

RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L]

Редирект сайта с https на http

Если необходимо сделать 301 редирект всего сайта с https на http, в файл прописывается следующее:

RewriteCond %{SERVER_PORT} ^443$ [OR]

RewriteCond %{HTTP} =on

RewriteRule ^(.*)$ https://name.site/$1 [R=301,L]

Изменение домена

В том случае. если необходимо перейти на другой домен, при этом сохранив SEO-позиции, в файл .htaccess прописывают следующее:

RewriteCond %{HTTP_HOST} ^www.old_name.ru$ [NC]

RewriteRule ^(.*)$ http://new_name.ru/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^old_name.ru$ [NC]

RewriteRule ^(.*)$ http://new_name.ru/$1 [L,R=301]

Редирект на страницу с другим url (без параметров)

Иногда возникает ситуация, когда необходимо изменить url страницы, то есть перенести данные с одной страницы на другую страницу, при этом не потеряв вес страниц. В этом случае в файл .htaccess прописывают следующее:

RewriteRule ^(.*)old_page.html$ http://vash-sait.ru/new_page.html [R=301,L]

Редирект для url (с параметрами)

Если адрес содержит параметр (например, http://name.site/articles.php?section=1, где параметром является «section=1» ), то прописывают следующую конструкцию:

RewriteCond %{QUERY_STRING} section=1

RewriteRule ^index.php http://name.site/articles.php? [R=301,L]

Редирект с index.php на главную страницу

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

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /index.php HTTP/

RewriteRule ^index.php$ http://name.site/ [R=301,L]

Редирект со страниц со слешем на без слеша (для всего сайта)

Для избегания дублей в файле .htaccess используют следующую конструкцию:

RewriteCond %{REQUEST_URI} !?

RewriteCond %{REQUEST_URI} !&

RewriteCond %{REQUEST_URI} !=

RewriteCond %{REQUEST_URI} !.

RewriteCond %{REQUEST_URI} ![^/]$

RewriteRule ^(.*)/$ /$1 [R=301,L]

Или более короткий вариант:

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_URI} ^(.+)/$

RewriteRule ^(.+)/$ /$1 [R=301,L]

Редирект со страниц без слеша на слеш (для всего сайта)

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

RewriteCond %{REQUEST_URI} !?

RewriteCond %{REQUEST_URI} !&

RewriteCond %{REQUEST_URI} !=

RewriteCond %{REQUEST_URI} !.

RewriteCond %{REQUEST_URI} !/$

RewriteRule ^(.*[^/])$ /$1/ [R=301,L]

301 редирект с 404 Not Found

Код 404 Not Found (страница не найдена) присваивается удаленной или несуществующей странице на сайте. Создание постоянного перенаправления с таких страниц актуально для контентных сайтов и крупных интернет-магазинов, где страницы часто удаляются по естественным причинам. Тогда возникает потребность перенаправить посетителей на одну из главных страниц сайта, чтобы они не уходили с ресурса при виде ошибки.

301 редирект для страниц 404 Not Found сделать совсем не сложно. Например, этот код перенаправит со всех 404-страниц на главную:

ErrorDocument 404 http://www.site.com/301.html

Однако делать такие редиректы в массовом порядке не рекомендуется, так как это может испортить SEO-статистику всего ресурса.

Финальный вид файла .htaccess

Пример файла htaccess, после добавления в него редиректов:

Options -Indexes

ErrorDocument 404 /404.php

php_flag register_globals off

php_value pcre.recursion_limit 1000

#Условия 301 редиректа


<IfModule mod_rewrite.c>

RewriteEngine On

# склейка зеркал


RewriteCond %{HTTP_HOST} ^my_site.ru

RewriteRule ^(.*)$ https://my_site.ru/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^my_site.ru

RewriteRule ^(.*)$ https://my_site.ru/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www.my_site.ru

RewriteRule ^(.*)$ https://my_site.ru/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www.my_site.ru$ [NC]

RewriteRule ^(.*)$ https://my_site.ru/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www.my_site.ru

RewriteRule ^(.*)$ https://my_site.ru/$1 [R=301,L]

# без слеша


RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_URI} ^(.+)/$

RewriteRule ^(.+)/$ /$1 [R=301,L]

</IfModule>

php_value default_charset utf-8

AddType 'text/html; charset=utf-8' .html .htm .shtml

Синтаксис для регулярных выражений в .htaccess

.

точка заменяет произвольный символ

[abc]

обозначает перечень знаков, совпадающих с буквами a, b, или с

[^abc]

список символов вне указанного диапазона (кроме a, b, с)

*

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

[abc]*

команда найдет идущие подряд символы из заданного набора

[^abc]*

приводит к противоположному эффекту

.*

заменяет любой набор символов

«.*»

ищет все подстроки между кавычками

^

начало строки (когда используется в начале выражения)

$

означает конец строки

w

цифра, буква или подчеркивание _

d

заменяет любую цифру

D

может заменить любой знак, кроме цифры

[0-9]

для замены любой цифры

[a-z]

для всех букв от a до z в нижнем регистре

[A-Z]

для каждой буквы от A до Z в верхнем регистре

[a-zA-Z]

любая буква от a до Z во всех регистрах

[a-Z]

аналогично

Важно учитывать, что настройка редиректа путем редактирования файла .htaccess  доступна исключительно для веб-серверов Apache.

Другие способы создания переадресации 301

Через PHP

Данный вариант подойдет тем, кто хорошо разбирается в web-программировании и PHP. Необходимо открыть файл index.php в корне CMS-движка и прописать там:

if($_SERVER['REQUEST_URI'] == "/index.php") {

 header("Location: /",TRUE,301);

 exit();

}

(в первой строке укажите старый url, а во второй — новый)

Второй способ — перенаправление при помощи отправки заголовков (скрипта):

<?php

  header("HTTP/1.1 301 Moved Permanently");

  header("Location: http://www.newdomain.ru/newdir/newpage.htm");

  exit();

?>

ASP-редирект

<%@ Language=VBScript %>

<%

Response.Status="301 Moved Permanently"

Response.AddHeader "Location", "http://www.new-url.com"

response.end

%>

ASP.NET редирект

Найдите в корне своего сайта файл web.config и вставьте в секцию синтаксис:

<script runat="server">

  private void Page_Load(object sender, System.EventArgs e)

  {

    Response.Status = "301 Moved Permanently";

    Response.AddHeader("Location","http://www.new-url.com");

  }

</script>

ColdFusion редирект

<.cfheader statuscode="301″ statustext="Moved permanently">

<.cfheader name="Location" value="http://www.new-url.com">

JSP (Java) редирект

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

<script type="text/javascript" src="redirect.js"></script>

<script type="text/javascript">

  location="https://yandex.ru";

</script>

CGI-скрипт на PERL

$q = new CGI;

print $q->redirect("http://www.new-url.com/");

Ruby on Rails

def old_action

headers["Status"] = "301 Moved Permanently"

redirect_to "http://www.new-url.com/"

end

Редирект в Nginx

if ($host = 'www.domain.com' ) {

  rewrite ^(.*)$ http://domain.com$1 permanent;

}

HTML-редирект

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

<meta http-equiv="refresh" content="5;https://livepage.pro">

Если поставить значение 0 вместо 5, то переадресация на https://livepage.pro произойдет моментально.

Однако для больших сайтов HTML-перенаправление делать сложно и затратно по времени, поэтому лучше отдать предпочтение другому варианту.

Редирект 301 в панелях управления сервера

Большинство панелей управления сервера предоставляют возможность настройки переадресации с кодом 301. Рассмотрим варианты решения этой задачи на примере двух популярных ПУ для VDS.

Cpanel

Как сделать 301 редирект - Cpanel

Нужно перейти в блок «Домены» => «Перенаправления». В появившемся окне выполнить следующее:

  • В строке «Тип» выбрать «Постоянный 301».

  • В строке «https://www» из выпадающего списка выбрать домен сайта (например, example.ru).

  • В строке «Перенаправляет на» указать для домена адрес http://example.ru.

  • В блоке «Перенаправление www» поставить галочку напротив «Перенаправлять только с www».

  • Сохранить изменения кликом на «Добавить».

ISPmanager

Как сделать 301 редирект в ISPManager

В этой панели можно вручную править файлы nginx.config или .htaccess, но есть и встроенный механизм переадресации. Например, для настройки редиректа на https/http нужно снять галочку с соответствующего пункта в разделе «WWW-домены».

Автоматическое создание переадресации

При отсутствии знаний и опыта самостоятельной настройки редиректа можно воспользоваться сервисами автоматической генерации:

  • Seomagnifier — 301 для www;

  • 301 Redirect Code Generator Tool — для доменов и страниц;

  • Generate .htaccess— для страниц, разделов сайтов, доменов.

Проверка корректности настроек 301 редиректа

Самый простой способ проверки переадресации – ручное тестирование. Для этого необходимо вставить в адресную строку браузера url сайта или страницы, с которой настроено перенаправление. Если при открытии будет доступен ресурс, на который настроен редирект, то переадресация выполняется правильно.

Для автоматической проверки можно воспользоваться специальными сервисами:

  • Redirect Checker, bertal.ru или Header Checker Tool для тестирования отдельных страниц;

  • программой Screaming Frog Seo Spider, способной просканировать весь сайт.

Существует ряд ошибок, которые следует избегать при настройке редирект 301:

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

  • установка временной переадресации вместо постоянной;

  • неправильный выбор типа редиректа;

  • перенаправление файла robots.txt;

  • непонимание разницы между rel=canonical и кодом 301;

  • редирект на нерелевантный контент;

  • переадресация, которая не приводит к 200-й странице.

Стоит отметить проблему создания цепочки ссылок, которая может привести к появлению циклического редиректа — ошибки с кодом «ERR_TOO_MANY_REDIRECTS». Наиболее распространенные причины возникновения такого бага – неправильная настройка в процессе создания переадресации, вирусная атака, слишком длинная цепочка редиректов. Не рекомендуется настраивать редирект, содержащий более пяти адресов. Оптимальной является прямая переадресация со старого на новый url.

Заключение

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

Инструментов для настройки корректной работы Permanent Redirect 301 существует достаточно много. Наиболее удобный и правильный – внесение записей в файл .htaccess. Недостаток этого метода в том, что он доступен только для веб-серверов Apache. При использовании IIS придется настраивать web.config. Для создания сложных правил переадресации более всего подходит PHP, но в этом случае без помощи программиста не обойтись. Еще одним вариантом настройки 301 редиректа может быть обращение к хостинг-провайдеру с целью подключения услуги web-форвардинга.

What is redirection?

Redirection is a way of forwarding the user to the URL that is different from the one they initially clicked on. Down below some of the most common types of redirection are listed.

how to do a 301 redirect

301 Moved Permanently

A 301 redirect is a permanent redirect which passes between 90-99% of link equity (ranking power) to the redirected page. 301 signals that the page has been moved to another URL and the old URL is outdated.

302 Found (HTTP 1.1) / Moved Temporarily (HTTP 1.0)

302 is a temporary redirect which passes 0% of link equity, and shouldn’t be used in most cases.
As of now, the internet runs on an HTTP protocol which dictates how URLs work. In two versions of this protocol, the HTTP response status code is different:

  • HTTP 1.0: 302 status code is «Moved Temporarily» — current page has been moved temporarily to another URL.
  • HTTP 1.1: the description phrase has been changed to «Found» — current page has been found.

307 Moved Temporarily (HTTP 1.1 Only)

A 307 redirect is the HTTP 1.1 successor of the 302 redirect. While the major crawlers will treat it like a 302 in some cases, it is best to use a 301 for almost all cases. The exception to this is when content is really moved only temporarily (such as during maintenance) and the server has already been identified by the search engines as 1.1 compatible.

Since it’s essentially impossible to determine whether the search engines have identified a page as compatible, it is generally best to use a 302 redirect for content that has been moved temporarily.

Other redirection types

There are also some other types of redirection: Meta Refresh or JavaScript redirection that are executed on the page level rather than the web server level. This is what a typical Meta Refresh redirect looks like:

<meta http-equiv="refresh" content="2;url=http://example.com/" />

It’s best not to use these types of redirect, as they are often used by spammers and doorway pages. Besides, they pass little to none of the link juice.

Examples of using redirects

Redirecting your domain to a non-www URL:

RewriteCond %{HTTP_HOST} ^www.site.com$ [NC]
RewriteRule ^(.*)$ http://site.com/$1 [R=301,L]

Redirecting your domain to a www URL:

RewriteCond %{HTTP_HOST} ^site.com$ [NC]
RewriteRule ^(.*)$ http://www.site.com/$1 [R=301,L]

To choose which URL to make canonical, consider:

  • which URL ranks higher in the SERPs;
  • which URL is more represented in the index.

Redirecting your domain to URL without a slash

When developing a website, it’s important to choose whether you want to add a slash to the links, because the search engines consider the links
— www.site.com/cat1
and
— www.site.com/cat1
to be different. Then, you’ll have to add the following code:

To delete the slash from the URLs:

RewriteCond %{HTTP_HOST} (.*)
RewriteCond %{REQUEST_URI} /$ [NC]
RewriteRule ^(.*)(/)$ $1 [L,R=301]

To add the slash to the URLs:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*[^/])$ $1/ [L,R=301]

To redirect the user from one page to another:

Redirect 301 /oldpage.html http://www.site.com/newpage.html

Redirecting the main page duplicates

This code ensures that if there are multiple versions of the direct link to the main page (index, etc.), they will all redirect to the canonical main page:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /([^/]+/)*(default|index|main).(html|php|htm) HTTP/ [NC]
RewriteRule ^(([^/]+/)*)(default|main|index).(html|php|htm)$ http://www.site.com/$1 [L,R=301]

Redirecting catalogs

If the URLs reflect the structure of a catalog, changes in the catalog will lead to changes in the URLs. In this case, use the following redirect:

RewriteRule ^(.*)/old-catalog/(.*)$ $1/new-catalog/$2 [R=301,L]

But, if the URL of the previous catalog comes right after the name of a domain: www.site.com/old-catalog, use this code:

RewriteRule old-catalog /(.*) / old-catalog /$1 [R=301,L]

If you’ve switched platforms or a CMS and only the URLs’ extension has changed, use this redirect:

RedirectMatch 301 (.*).php$ http://www.site.com$1.html

Examples of using redirection to avoid duplicate pages

Redirecting (sub-)domains

In case you’ve bought several domains with multiple TLDs, OR used a subdomain to develop a new website and forgot to block it from being indexed by the search engines. Either way, you have to set up redirection to the root domain:

RewriteCond %{HTTP_HOST} !^www.site.com
RewriteRule ^(.*)$ http://www.site.com/$1 [R=301,L]

That way, all the (sub-)domains like www.site.org, www.site.net, test.site.com, will redirect to www.site.com

Deleting multiple slashes/hyphens from the URLs

Sometimes, user can accidentally type in multiple slashes, e.g. www.site.com/catalog////page-1.html. In this case, you have to set up a 301 redirect to a page with a single slash www.site.com/catalog/page-1.html:

RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]

In the same way, you can set up a redirect from a URL with multiple hyphens (for example, www.site.com/catalog/page—1.html) to www.site.com/catalog/page-1.html:

RewriteCond %{REQUEST_URI} ^(.*)--(.*)$
RewriteRule . %1-%2 [R=301,L]

Redirecting from any URL to a lowercase URL

The search engines notice the letter case, so it’s best to have your URLs in lowercase. If you haven’t developed your website with this in mind, you can use this PHP-script:

$lowerURI=strtolower($_SERVER['REQUEST_URI']);
if($_SERVER['REQUEST_URI']!=$lowerURI)
{
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://" . $_SERVER['HTTP_HOST'] . $lowerURI);
exit();
}

How to move your website to a new domain? The optimal strategy for a 301 redirect

According to the most popular search engines, the best strategy for moving to a new domain is:

  • mounting a page-by-page 301 redirect from the old site to the new one;
  • don’t set up a redirect from robots.txt — add the Host directive to the new domain instead.

In this case, the code on the former website will have to look something like this:

RewriteCond %{REQUEST_FILENAME} robots.txt$ [NC]
RewriteRule ^([^/]+) $1 [L]
RewriteCond %{HTTP_HOST} !^www.site.com
RewriteRule ^(.*)$ http://www.site.com/$1 [R=301,L]
а файл robots.txt для старого сайта:
User-agent: Yandex
Disallow:
Host: newsite.com

Generating 301 redirects

If you’re not particularly tech-savvy, you can use the online services for generating basic redirects:

http://www.webconfs.com/htaccess-redirect-generator.php
http://www.rapidtables.com/web/tools/redirect-generator.htm
Just enter your data and get a code for redirection between domains, directories, and URLs.

How to test the 301 redirect

With every change in 301 redirect, you need to test the site’s performance:

  • whether it’s working (check the main page);
  • go through the main sections and webpages of the site.

301 redirect VS Canonical — which one to use & when?

Minor details aside, in order to understand what exactly do we want to say, Google offers some clear-cut rules. In very simple terms, this is how the search engines understand our commands:

301: okay, google (or any other search engine), my page isn’t there anymore and it’s been permanently moved to a new URL. Please, delete the old link from the index, and pass the link juice to the new page.

Canonical: okay, google, I’ve got multiple versions of the same page (or its content), so, please, index only the canonical version. I will keep the other versions for people to see, but don’t index them, please, and pass the link juice to the canonical page.

When is it better to use a 301 redirect?

  • This is a preferred method by default;
  • For pages, that have beenmoved permanently, or their URLs have been changed;
  • For domains, if you’ve moved your website to the new domain;
  • For 404 pages. For example, if a certain product has been deleted from the catalog, you can set up a redirect to a page with a similar product, or to the URL of the product category.

When is it better to use rel= «canonical»?

  • If you can’t set up 301 redirects or it won’t be time-efficient;
  • For duplicate content, if you want to keep both versions (for example, pages with different clothing sizes);
  • When you have multiple URLs leading to the same page (catalog categories, pages for tracking the traffic from affiliate links, etc.);
  • For cross-domain resource sharing, if you want to transfer data between pages that have different origins (domains, for example).

To sum it up

Both solutions pass the link juice and both are ranked by Google equally. 301 redirect is a bit more preferred, though.

Redirection mistakes

  • Redirection chains (avoid them to maximize the speed and the link juice flow of the website);
  • Using the wrong type of redirect (to make the right decision, you have to consider all the details);
  • Setting up internal redirects without rewriting the URLs of the links. You have to make sure that links on your website don’t lead to pages with the redirect;
  • Redirecting to irrelevant pages/content. Your links should always lead either to similar pages or to the section of the site that included the requested page;
  • The wrong choice of either rel=canonical or 301 direct (see above);
  • Redirecting robots.txt (it’s better to add the Host directive);
  • Any redirect, which doesn’t lead to a page with a 200 status code (every link should lead to a properly working page with a 200 status response. Otherwise, don’t confuse the crawlers and just show the 404 Error page).

Hopefully, this 301 how-to guide will be your cheat sheet and will help you to use a 301 redirect on your website.

If you have any questions, ask them down below. I will try my best to help you!

Read also:
Essential on-site SEO factors.

Nov 23, 2017 10:00:15 AM |
301 Moved Permanently: What It Is and How to Fix It

A close look at what a 301 Moved Permanently response code is, including troubleshooting tips to help you resolve this error in your own application.

A 301 Moved Permanently is an HTTP response status code indicating that the requested resource has been permanently moved to a new URL provided by the Location response header. The 3xx category of response codes are used to indicate redirection messages to the client, such that the client will become aware that a redirection to a different resource or URL should take place.

It can be a challenge to differentiate between all the possible HTTP response codes and determine the exact cause of a message like the 301 Moved Permanently code. There are dozens of possible HTTP status codes used to represent the complex relationship between the client, a web application, a web server, and often multiple third-party web services, so determining the cause of a particular status code can be difficult. In this article we’ll examine the 301 Moved Permanently code by looking at a few troubleshooting tips, along with some potential fixes for common problems that might be causing this issue, so let’s get started!

The Problem is Server-Side

All HTTP response status codes that are in the 3xx category are considered redirection messages. Such codes indicate to the user agent (i.e. your web browser) that an additional action is required in order to complete the request and access the desired resource. Unlike gateway related 5xx response codes, like the 502 Bad Gateway Error we’ve looked at recently, which may indicate issues either on an upstream server or the client, the 301 Moved Permanently code generally indicates an issue on the actual web server hosting your application.

That said, the appearance of a 301 Moved Permanently is usually not something that requires much user intervention. Most browsers should automatically detect the 301 Moved Permanently response code and process the redirection action automatically. The web server hosting the application should typically include a special Location header as part of the response it sends to the client. This Location header indicates the new URL where the requested resource can be found. For example, if a request comes in to access the URL https://airbrake.io, but the web server is configured to forces redirection to a secure version using https, the server response will include the Location: https://airbrake.io header. This tells the browser that it should redirect this request (as well as all future ones) to https://airbrake.io to the secured URL of https://airbrake.io. In most cases, the browser will automatically detect this 301 Moved Permanently response code, read the new Location URL, and redirect the request to that new location. It is considered best practice to use a 301 Moved Permanently redirection to transition a user agent from HTTP to the secure HTTPS. Thus, if you attempt to go to the insecure URL of https://airbrake.io right now, you’ll automatically be redirected to the HTTPS version of the site (https://airbrake.io).

Since the 301 Moved Permanently indicates that something has gone wrong within the server of your application, we can largely disregard the client side of things. If you’re trying to diagnose an issue with your own application, you can immediately ignore most client-side code and components, such as HTML, cascading style sheets (CSS), client-side JavaScript, and so forth. This doesn’t apply solely to web sites, either. Many smart phone apps that have a modern looking user interface are actually powered by a normal web application behind the scenes; one that is simply hidden from the user. If you’re using such an application and a 301 Moved Permanently occurs, the issue isn’t going to be related to the app installed on your phone or local testing device. Instead, it will be something on the server-side, which is performing most of the logic and processing behind the scenes, outside the purview of the local interface presented to the user.

All of that said, if your application is generating 301 Moved Permanently codes improperly or unexpectedly, there are a number of steps you can take to diagnose the problem.

Start With a Thorough Application Backup

As with anything, it’s better to have played it safe at the start than to screw something up and come to regret it later on down the road. As such, it is critical that you perform a full backup of your application, database, and so forth, before attempting any fixes or changes to the system. Even better, if you have the capability, create a complete copy of the application onto a secondary staging server that isn’t «live,» or isn’t otherwise active and available to the public. This will give you a clean testing ground with which to test all potential fixes to resolve the issue, without threatening the security or sanctity of your live application.

Diagnosing a 301 Moved Permanently Response Code

A 301 Moved Permanently response code indicates that the server believes that the requested resource is invalid and that the request should be redirected to a new, «proper» URL. I use the word believes here because it’s entirely possible that the server is misconfigured or bugged in some way, which is causing it to provide 301 Moved Permanently codes for resources/URLs that are totally valid. Thus, a large part of diagnosing the issue will be going through the process of double-checking what resources/URLs are generating 301 Moved Permanently response codes and determining if these codes are appropriate or not.

That said, if your application is responding with 301 Moved Permanently codes that it should not be issuing, this is an issue that many other visitors may be experiencing as well, dramatically hindering your application’s ability to service users. We’ll go over some troubleshooting tips and tricks to help you try to resolve this issue. If nothing here works, don’t forget that Google is your friend. Don’t be afraid to search for specific terms related to your issue, such as the name of your application’s CMS or web server software, along with 301 Moved Permanently. Chances are you’ll find others who have experienced this issue and have come across a solution.

Troubleshooting on the Server-Side

Here are some additional tips to help you troubleshoot what might be causing the 301 Moved Permanently to appear on the server-side of things:

  • Check the Server Configuration Files — Your application is likely running on a server that is using one of the two most popular web server softwares, Apache or nginx. At the time of publication, both of these web servers make up over 84% of the world’s web server software! Thus, one of the first steps you can take to determine what might be causing these 301 Moved Permanently response codes is to check the configuration files for your web server software for unintentional redirect instructions.

To determine which web server your application is using you’ll want to look for a key file. If your web server is Apache then look for an .htaccess file within the root directory of your website file system. For example, if your application is on a shared host you’ll likely have a username associated with the account on that host. In such a case, the application root directory is likely something like /home/<username>/public_html/, so the .htaccess file would be at /home/<username>/public_html/.htaccess.

If you located the .htaccess file then open it in a text editor and look for lines that use RewriteXXX directives, which are part of the mod_rewrite module in Apache. Covering exactly how these rules work is well beyond the scope of this article, however, the basic concept is that a RewriteCond directive defines a text-based pattern that will be matched against entered URLs. If a matching URL is requested by a visitor to the site, the RewriteRule directive that follows one or more RewriteCond directives is used to perform the actual redirection of the request to the appropriate URL. Therefore, if you find any strange RewriteCond or RewriteRule directives in the .htaccess file that don’t seem to belong, try temporarily commenting them out (using the # character prefix) and restarting your web server to see if this resolves the issue.

On the other hand, if your server is running on nginx, you’ll need to look for a completely different configuration file. By default this file is named nginx.conf and is located in one of a few common directories: /usr/local/nginx/conf, /etc/nginx, or /usr/local/etc/nginx. Once located, open nginx.conf in a text editor and look for the return or rewrite directives. For example, here is a simple block directive (i.e. a named set of directives) that configures a virtual server by creating a redirection from invalid-domain.com to the proper valid-domain.com URL:

server {
listen 80;
listen 443 ssl;
server_name invalid-domain.com;
return 301 $scheme://valid-domain.com$request_uri;
}

Rewrite directives in nginx are similar to the RewriteCond and RewriteRule directives found in Apache, as they tend to contain more complex text-based patterns for searching. Either way, look through your nginx.conf file for any abnormal return or rewrite directives and comment them out before restarting the server to see if the issue was resolved.

  • Check the Logs — Nearly every web application will keep some form of server-side logs. Application logs are typically the history of what the application did, such as which pages were requested, which servers it connected to, which database results it provides, and so forth. Server logs are related to the actual hardware that is running the application, and will often provide details about the health and status of all connected services, or even just the server itself. Google «logs [PLATFORM_NAME]» if you’re using a CMS, or «logs [PROGRAMMING_LANGUAGE]» and «logs [OPERATING_SYSTEM]» if you’re running a custom application, to get more information on finding the logs in question.
  • Application Code or Script Bugs — If all else fails, it may be that a problem in some custom code within your application is causing the issue. Try to diagnose where the issue may be coming from through manually debugging your application, along with parsing through application and server logs. Ideally, make a copy of the entire application to a local development machine and perform a step-by-step debug process, which will allow you to recreate the exact scenario in which the 301 Moved Permanently occurred and view the application code at the moment something goes wrong.

No matter what the cause, the appearance of a 301 Moved Permanently within your own web application is a strong indication that you may need an error management tool to help you automatically detect such errors in the future. The best of these tools can even alert you and your team immediately when an error occurs. Airbrake’s error monitoring software provides real-time error monitoring and automatic exception reporting for all your development projects. Airbrake’s state of the art web dashboard ensures you receive round-the-clock status updates on your application’s health and error rates. No matter what you’re working on, Airbrake easily integrates with all the most popular languages and frameworks. Plus, Airbrake makes it easy to customize exception parameters, while giving you complete control of the active error filter system, so you only gather the errors that matter most.

Check out Airbrake’s error monitoring software today and see for yourself why so many of the world’s best engineering teams use Airbrake to revolutionize their exception handling practices!

301 Error Code

Introduction

Learn about 301 redirects and the most common errors so you can avoid them in
the future. Fortunately, you’ve found your way here.

Think of it as if you’re creating a brand new webpage or an entire website
from scratch. Alternatively, you may be moving your website. Your domain name
may contain a typo. You’ve concluded that using the same URL is no longer
feasible. What are you doing?

A 301 permanently relocated status code is what you use. The purpose of these
codes is to redirect your customers to a different location. «The requested
document has been permanently relocated.» Users will try to access a page, but
will instead be redirected elsewhere.

You need to know the
301 status code, as well as how to find and fix 301 errors, here.

What Does 301 Permanently Moved Mean?

HTTP status codes
come in a wide variety of flavors. There are a variety of ways to tell the
user if a specific HTTP request has been successful. In total, there are five
levels:

  • Responses that provide data (such as 100 Continue and 101 Switching
    Protocols)
  • Successful outcomes
  • Reroutes traffic
  • Mistakes by the user (like
    404 Page Not Found)
  • as well as server issues

There is a redirection indicated by the 3xx HTTP status code. Instead of the
original URL, users and search engines will be redirected to a new one. There
are a variety of 3xx status codes, such as 302, 303, and 307, each with their
unique interpretation.

301 status codes should be used when you’re permanently changing one URL for
another. In other words, the old URL will be redirected to the new one for
people and bots alike.

Website.com/blog redirects to blog.website.com

It would sound something like this to a real person:

Visitor: For the time being, this page has been relocated, and we have
no plans to return it.

Browser: I see now. I’ll direct your existing customers to the new
URL.

There will be no need for the old URL, as it will no longer appear in the
search results. The old URL’s link equity will be transferred to the new
URL.

As a result, whenever you’re doing a site migration or removing an old page
and replacing it with a new one, you’ll want to perform a 301 Moved
Permanently redirect.

How do 301 and 302 redirections differ?

A 301 redirect is superior to a 302 redirect. Have trouble deciding which
one to use?

The fact that you’re feeling this way isn’t unique.

Even in 2019, website owners are unsure of which type of redirect is best for
search engine optimization (SEO).

A redirect can be useful for a variety of reasons. Below are the most
frequently used justifications:

  • You’ve launched a brand-new site. 
  • Creation of a new page for you.
  • There is a problem with your URL.

For example, you’re working on an issue with a page and want to redirect users
to another page.

The decision is heavily influenced by the redirect’s intended outcome. When it
comes to SEO, it’s important to know the difference between the two.

Search engines need to be informed that a website or page has been permanently
relocated by a 301 redirect. If you’re moving a website or creating a new one,
you should use an HTTP 301. Usage of 301 is appropriate if you’re joining two
websites together. However, 301 is also useful if you’re making modifications
to the URL that are not meant to be reversed.

Using a 302 redirect lets search engines know that a website or page has been
temporarily redirected elsewhere. If you’re redesigning or updating a website
or a page, you should use this redirect. You can also use the redirect to test
out a new page and get feedback from customers. Only use a 302 redirect if you
intend to bring the old website or page back online in the future.

A 301 redirect lasts how long?

It is typical for a 301 redirect to remain in place for a year or more. Check
to see if you’re new URL is still being sent to users after that.

Fixing 301 redirects is a question I frequently get

Error 301 is a common occurrence for website owners of all skill levels. To
keep your website in good working order, it’s important to know what’s wrong
and how to fix it. When dealing with these kinds of issues, regular website
maintenance is a must, and here are the most common and best ways to resolve
them.

Check to see if your HTTP version is redirecting to your HTTPS version.

Using HTTPS on your site can help protect the personal information of your
site’s visitors. For additional information, Google uses HTTPS as a ranking
factor. To put it another way, not encrypting your website traffic with HTTPS
can harm your search engine results. For the sake of everyone’s safety online,
Google hopes that this move will encourage all website owners to make the
switch from HTTP to HTTPS. It’s 2019 and HTTPS is a no-brainer.

However, if your users are not redirected to the secure HTTPS version, using
HTTPS is of no use. In other words, you’ll need to use an HTTP 301 to switch
between HTTP and HTTPS.

Check the URL bar of your homepage to see if the 301 redirect works between
your two versions. The following is what you’ll see:

https://www.technologycrowds.com/

Enter the URL
https://www.technologycrowds.com/  by removing the «s» from the beginning. A redirect to the secure HTTPS
version of your site should occur if all goes well.

Get rid of all of the 301 redirects on your website

To better crawl your site, Google consults your
sitemap
file. However, since your redirected pages don’t exist, Google has no reason
to crawl them.

301 error status codes can be removed by performing the following steps:

Yourdomain.com/sitemap.xml can be found at this location (keep in mind that
your sitemap URL might be different as there are exceptions).

Use a URL Extractor to download a list of all of your URLs in one place.

  • Use any free tool to paste the list.
  • Use a 301 status code to narrow the results.
  • Replace the 301 URLs in the sitemap file with the final URL. 
  • Delete the 301 URLs from the sitemap file.
  • Redirect chains are to be avoided at all costs.

When the original URL and the final URL are connected by more than one
redirect, this is known as a redirect chain. If you want to see an example of
this, look at Page 1. Nevertheless, Google cautions against the use of
redirect chains, citing the negative impact on user experience (UX) and the
resulting slowdown on site performance.

Link farms are bad for SEO, too. Only about 85% of link equity is passed
through 301 redirects, according to industry estimates. In other words, the
more redirects there are, the worse the situation.

Ensure that the final URL is redirected to. A few pointers:

Redirect chains can be found using a tool like this.

The redirect chain should be replaced with a single 301 redirect once you’ve
found them. In place of Page 1, Page 2, and then Page 3, the redirect goes to
Page 1 and then Page 3.

In addition, you can replace internal links to redirected pages with direct
links to the final URL.

Remove redirect loops

URLs that are linked together can create a redirect loop when one of them
redirects users back to another URL. There are many examples of this, such as
the following:

As soon as possible, you’ll want to address this problem.

Use a free tool to scan up to 100 URLs for errors indicating that the maximum
number of redirects has been exceeded.

You can fix redirect loops in two ways once you find them:

If you don’t want the URL to redirect, change the HTTPS response code to
200.

You should fix the final destination URL if the URL is supposed to reroute.

Your redirects need to be fixed.

If a link is broken, it takes you to a page that doesn’t exist! Page 1 (301)
> Page 2 (302), for example (404). Your website’s search engine rankings
and user experience could suffer as a result.

To check for broken redirects in batches of 100, use the tool we mentioned
above.

You can fix any errors you find by:

  • Reviving a long-dead page
  • Deleting the redirected URL’s in-links.

Redirects from 302 to 301 should be used instead.

If you want to move permanently, you should never use 302 redirects. Removing
or replacing an HTTP response status code 302 redirect that is in place
because of a long-term move is the best course of action.

301 redirect pages that receive traffic should be examined.

This code tells the browser that a page has permanently relocated to a new
URL. There should be no organic traffic to that page. Chances are that Google
will notice the HTTP 301 if you recently added it.

Use a tool like Moz, SemRush, or Ahrefs to look for redirected pages that are
still receiving organic traffic.

Remove the pages from your sitemap and re-submit them through Google Search
Console once you’ve located them.

The most important things to remember

A 301 redirect is a permanent way of sending a URL to a new location. Search
engines and website visitors alike will be alerted to the URL’s new location
if you do this.

You must have a strategy in place and use redirects wisely. Organic traffic
can be greatly increased by correctly implementing HTTP 301. Follow the advice
above if you’re concerned that your website has unresolved 301 Moved
Permanently errors.

How to Fix 301 Moved Permanently Error?

How to Fix 301 Moved Permanently Error?

Before we study whole about the 301 Moved Permanently Error, let’s starts a small discussion upon the redirects.

Are you not familiar with the redirects? Do you ever feel like how to create a redirect in WordPress, why do you need, and when you should use redirects?

The 3xx HTTP Status Code Series

The 3xx HTTP Status Code series indicates that the client must take additional action to complete the request and access the desired resource. Mostly these status codes are used in URL redirection. The 301 redirects are considered best for upgrading users from HTTP to HTTPS.

What is a Redirect in WordPress?

A redirect is a way to send a quick message to your readers to tell them that the page they want to visit has moved, so their browser can automatically point them to the new page of your choice. There are the different type of redirects available, and some of them are 301, 302, and 307 redirects.

What is 301 Moved Permanently?

301 status code indicates that the URL of the requested resources has changed and a new URL is assigned, in the response. In short, it tells that the URL has Moved Permanently and it will pass the 90% of the Search Engine Link Juice to the new URL.

Where is the problem?

The problem is on the Server Side. As I told you, the 3xx series codes are considered to be redirection messages. Such status codes are generated in response when there is an additional action is required to complete the request on the active web server.

The 301 Moved Permanently code shows an issue on the actual web server hosting your website. Most of the web browsers are automatically detect the 301 Moved Permanently response code and process the redirection action automatically.

Let’s have a small example to understand how it occurs.

Suppose you are accessing a URL like http//:tech-banker.com, but the web server is configured to force redirection to a secure version using https. It informs the browser regarding redirecting the request from http://tech-banker.com to the secured https://tech-banker.com.

In most cases, the browser will automatically detect the 301 Moved Permanently response code after that it will read the new location URL and redirect the request to that new location.
Thus, if you attempt to go through http://tech-banker.com right now, you’ll automatically be redirected to the HTTPS version of the site: https://tech-banker.com.

Start With a Backup

Before moving, it is suggested to take a complete backup of your website. You can use any WordPress backup plugin to backup your site. You may use Backup Bank to backup your site. It is freely available on wordpress.org. With the help of Backup Bank, you can take backup manually even you can also schedule your site back up.

Diagnoses for 301 Moved Permanently Response Code

The 301 Moved Permanently indicates that the URL or resources you are trying to access are not valid and must be redirected to a new URL.

Here are some steps that may help you in troubleshooting this error.

Method 1) Check the Server Configuration Files

Apache or Nginx are the two most popular web servers. Your site is probably running on one of these web servers. Thus, the first step you can take to determine the cause of 301 response code is to check the configuration files for your web server.

If you are on Apache Web Server then, Look for a .htaccess file within the root directory of your website file system. You can find the file at /home//public_html/.htaccess . If you found the .htaccess file, open it in a text editor and look for RewriteXXX directives, which are part of the mod_rewrite module in Apache.

These directives define a text pattern that will match against the requested URL.

RewriteCond directives are used to perform the actual redirection of the request to the appropriate URL. If you find any strange RewriteCond or RewriteRule directives in the .htaccess file, try temporarily commenting them using the # character prefix and restarting your web server to see if the issue resolved or not.

You can also try deleting the .htaccess file and recreate it. It is quite easy to recreate a .htaccess file. Here are the steps:

1. Login to your WordPress admin and navigate to the Settings Menu.

2. Move to the Permalinks Menu and click on the Save Changes button.

Not Working Permalinks Option In Settings

This way, you have a new bug free .htaccess file. On the other hand, if your server is running on nginx then, you’ll need to look for an entirely different configuration file.

nginx.conf is the file and is located in: /usr/local/nginx/conf, /etc/nginx or /usr/local/etc/nginx

Once found, open nginx.conf in a text editor and look for the rewrite directives. Check for any abnormality and comment them out before restarting the server to see if the issue was fixed.

Method 2) Check the Logs

Logs provide the details about the health and status of all the server. They tell about the nature and the type of the error. They tell, on which file it is appearing, line number where it is appearing. By so, it becomes easy to detect and correct the error.

Method 3) Custom Code or Script File

It may be that your custom code is generating the error. Try to diagnose the issue by manually debugging your custom code. Remove the code snippet or the file and check the tab with the error.

Why do you need to use a 301 Moved Permanently?

Let’s take a look at why it is necessary to understand the use of 301 redirects. The reason to use 301 HTTP Status Code is you want your user to redirect to a new page when a page or post on your site has moved permanently.

Below are some points that will show you when you need to use a 301 redirect in WordPress.

1. When you plan to delete a post or page.

2. When you plan to change the permalinks of your post or page.

Now, the answer to why you need to create a 301 redirect is, it will not only save your website from showing the 404 Not Found message on your screen but also save it from degrading the site’s search engine ranking.

The 301 Moved Permanently error, tells search engines that the page you are trying to access has permanently moved to a new location.

Conclusion

It’s recommended to set up 301 redirects in WordPress when you change the URL (permalinks) of your posts and pages or move your website from one domain to another. The 301 redirects are considered best for upgrading users from HTTP to HTTPS.

WordPress Plugins


  • Backup Bank


  • Captcha Bank


  • Captcha Booster


  • Clean Up Booster


  • Clean Up Optimizer


  • Coming Soon Booster


  • Contact Bank


  • Facebook Like Box


  • Gallery Bank


  • Gallery Master


  • Google Maps Bank


  • Limit Attempts Booster


  • WP Mail Bank


  • WP Mail Booster

How to Fix 301 Moved Permanently Error? 1

Alliance  · 
March 16, 2021

A 301 redirect is an essential when setting up a new webpage or migrating a website to indicate that what you’re looking for – is no longer available – and has permanently moved to a new location. But what if your 301 moved permanently status codes isn’t working as intended or is bringing up the wrong resource? This type of website maintenance is essential in making sure your website is healthy, we will explain the common types of redirect issues and errors and how to fix them. 

What is a 301 Moved Permanently Redirect?

Each time you visit a website, there is a request sent from your browser to a website’s server. The web server receives this request, processes it, and sends along an HTTP header and HTTP status code. This HTTP status code normally will not be seen by someone visiting the website unless there is an error. If a server responds with an HTTP status code message, that is its way of communicating that there is some sort of an error. Within each type of HTTP status code, there is a category type that can be identified by a number that relates to the reason as to why the error occurred.

301 Moved Permanently

In the case of a 301 redirect, this type of HTTP status code occurs when there was supposed to be a redirection of a request to a new URL link.  This HTTP status code falls under the 3xx category of response codes, all of which are redirection-related requests. 

In the case of the 301 redirect, the problem occurs when there is an issue communicating a redirection request from an old to a new permanent URL link on a website. This type of error can occur when updates or changes are made to a website, but the server response redirecting the user to the new URL link has failed.

Why Do 301 Moved Permanently Occur?

Since the 3xx category of HTTP status codes are considered redirection messages, this indicates that additional action is necessary to access the website. Unlike 5xx HTTP status codes that relate to communication issues between two servers, the 301 moved permanently error occurs from an issue from the inbound website’s URL linking, and not the client trying to access it. While most browsers will automatically detect a 301 moved permanently response code and process a redirection request immediately, if the URL is not linked properly, a 301 error message will appear. Some other reasons 301 errors occur include:

  • New creation of a website
  • New webpage was created
  • Broken URL links
  • Fixing a webpage and want it to redirect to another page

How Can 301 Errors Damage a Website’s Reputation?

301 errors can impact a brand’s reputation in two ways — through search engine rankings and user experience. If your website has redirect request errors, search engines will not properly index it, and therefore decrease search rankings from an inability to detect page content. 301 errors also cause frustration for visitors as they are unable to find important content on specific pages of a website.

How do you fix a 301 error message?

1. Check Your Htaccess Files for Errors in URL Linking

Most websites run on one of these two types of popular server software — Apache. Within these server applications you will then look into the htaccess file within the root directory of your website files, as this will help determine where any redirection instructions are located.

What is an Htacess File?

Htacess stands for hypertext access, and is a type of server configuration file. Each file contains configuration directives towards a server within a directory. In simpler terms, each htaccess file basically gives instructions to a server, which could include passcode requirements for certain areas of a directory, as well as configuration to automatic redirects on certain areas of a website. If you need to update an htaccess file, it is important to ensure the file is properly titled ‘.htaccess’ only.

In order to locate the htaccess file in Apache, you can click on the username of your account associated with your server hosting. Once you have located the htaccess file within your directory, you can open it in a text editor and locate the lines Rewrite directives, which will allow you to modify these to ensure there are matching URL links for any redirects within your website.

There are two types of Rewrite directives that can be modified:

RewriteCond

RewriteRule

You will want to go through both of these within the htaccess file to make sure there aren’t any redirects to URLs that no longer exist. If there is, you can temporarily remove them and restart your website server to see if that resolves the issue.

If your server runs on nginx, your rewrite directives are identified as return or rewrite directives as opposed to RewriteCond and RewriteRule.

2. Use a Third Party Tool to Check for Any 301 Redirects

The free tools below are a great way to run a quick website audit and give some insights on any 301 moved permanently errors that might need to be modified.

https://www.redirect-checker.org/

https://httpstatus.io/ 

https://sitechecker.pro/redirect-checker/ 

3. Backup Your Website

Before trying to diagnose any website related server issues, a first recommendation would be to perform a full backup of your website database before attempting any of the steps below. This will ensure that no data loss will occur when trying to resolve a 301 Moved Permanently Error. 

4. Check Your Server Logs

Checking your server log will allow you to better understand a server’s current status. The server logs can help indicate any specific files that might be causing 301 error messages, allowing you to easily catch and adjust these files manually. 

5. Check Your Sitemap

Search engines use your sitemap to crawl a website so it is important to make sure there are no 301 errors embedded into your URLs. If you have any 301 status codes for nonexistent pages, you will want to make sure these are removed. This can be done by:

  • Accessing your website’s sitemap
  • Download a full list of your URLS
  • Filter for any 301 status codes within the list
  • Delete the 301 status codes and replace them with the correct URL update

6. Check Any Custom Code Files

If you have any custom code embedded into your website with errors, it may cause redirect issues. The easiest way to test this is to remove the line of custom code and refresh the page to see if the error message goes away to understand if this was the root of the problem.

7. Change any HTTP Response Codes to 200 If You Do Not Want A Redirect

Once you have identified the 301 redirects on your website, you can alter any unintentional redirects by changing the response code to the 200 category.

8. Remove Any Redirect Chains or Loops

A redirect chain occurs when there is more than one redirect between two URL links. First identify if any of these chains exist, then replace them with a direct link to the final URL.

A redirect loop is a communication error that occurs when one URL redirects back to another URL within that chain, causing a 301 error. You will want to check your URL list for any 301 redirects to understand if any of these loops or chains exist within your website.

9. Fix Any Broken Redirects

Broken redirects occur when a URL links to a page that no longer exists. You can identify broken redirects using the same steps mentioned above:

  • Access your website sitemap
  • Download a list of your URLS
  • Filter the list for any 301 status codes
  • Bring back the pages that no longer exist or update the URL to reflect the correct page it should be redirected to

Since both search engines and visitors use 301 redirects as a way to identify a new page destination, it is important that these links are updated properly to reflect the appropriate URL where they should be linked. These error messages can negatively impact both search engine rankings and user experience if unnoticed.

Понравилась статья? Поделить с друзьями:
  • Ошибка 3008 на опель астра
  • Ошибка 301 указанный идентификатор кассы заблокирован или не существует
  • Ошибка 3007 при обновлении wot
  • Ошибка 301 пропуски зажигания цилиндр 1
  • Ошибка 30064 dji mini 2