Все о 301 редиректе с примерами
301 Редирект — это способ постоянного перенаправления поисковых систем и посетителей сайта на адрес, который отличается от изначально запрашиваемого. Такой ответ сервера указывает на то, что старый url утратил актуальность, страницу переместили. После переиндексации Google поймет куда вы теперь хотите вести посетителей и станет предлагать пользователям новый адрес.
Удивительно, но факт: с помощью редиректа можно превратить потерю в победу и привлечь на свой ресурс еще больше трафика. Но об этом чуть позже.
Если вы хотите сделать правильную настройку 301 редиректа, обязательно изучите наше пошаговое руководство с примерами кода на все случаи и различными лайфхаками.
Для чего используется 301 редирект?
Код 301 — эффективный, простой в реализации вариант переадресации web-страницы. Это удобный способ сохранения рейтинга конкретной страницы сайта.
Основные причины, чтобы добавлять 301 редирект:
- сохранение «накопленных пользовательских сигналов» контента
- с передачей ссылочного веса новой странице;
- перенаправление трафика из других адресов на нужный;
- в случае ребрендинга и смены домена, чтобы не потерять клиентов;
- перемещение страниц;
- склейка (с www и без, http и https);
- удаление дублей страниц.
Внимание! Остановите выбор на адресе, который имеет стратегически большее значение, является предпочтительным для посетителей и поисковых систем.
Редирект можно назвать своеобразной палочкой-выручалочкой. В случае переезда всего сайта или отдельных страниц он сохранит все плоды проделанной работы: авторитет доменного имени и ранжирование в поиске. Главное — использовать перенаправление по назначению.
Сегодня вы получите 22 конкретных примера установки кода 301 и пять важных рекомендаций. С последних и начнем!
Советы по перенаправлению
Важно! Ошибки в настройках редиректов уменьшают эффект их использования.
1. Избегайте редиректов, идущих друг за другом. Каждая последующая переадресация увеличивает нагрузку на сервер, уменьшает эффективность редиректов.
Пример последовательных редиректов:
Правильным в данном примере должен быть редирект с 1 шага на 3й.
2. Размещайте правила редиректов от частных правил к общим так как противоречия частных общим могут вызывать их не срабатывание. Если частные будут ниже общих, в случае противоречий правил будут срабатывать общие как те, что идут первее по списку.
3. Из-за того что браузеры обычно запоминают перенаправления, лучше проверять код состояния HTTP через специальный сервис.
4. Переадресация не должна быть циклической, то есть странице нельзя ссылаться на саму себя.
Пример циклического редиректа: со страницы без слеша в конце URL стоит 301 редирект на страницу со слешем, на которой стоит 302 редирект обратно:
5. Полезный редирект — тот, что ведет на страницу, которая во всех нюансах повторяет запрашиваемую.
Популярные виды редиректов
Желаете узнать, как сделать переадресацию? Сначала надо ознакомиться с названиями и особенностями самых используемых статусов.
301
Это постоянный редирект, обозначающий, что старый адрес страницы стоит считать устаревшим, контент находится на новом месте. Передает на новый документ почти весь (нет точных данных) ссылочный вес и склеивает накопленные внутренние метрики.
302
Представляет собой временный редирект. Не склеивает накопленные внутренние метрики страницы.
Статус ответа сервера зависит от версии протокола HTTP:
- HTTP 1.0 — текущая публикация временно перемещена на другой url (Moved Temporarily);
- HTTP 1.1 — документ не найден (изменения ответа на Found).
307
307 Moved Temporarily подходит лишь для исключительных случаев — действительно кратковременного переезда контента, например, при техническом обслуживании.
Meta Refresh
Обновления Meta являются переадресациями, которые осуществляются не на уровне сервера, а на самой странице. Чаще всего такой код ответа связан с пятисекундным обратным отчетом, дополненным текстом «Если переход не произошел за пять секунд, нажмите здесь».
Этот медленный статус относится к не рекомендованным SEO-техникам — он может привести к ухудшению поведенческих факторов и проседанию веб-страницы в органической выдаче.
Важно! В использовании постоянного редиректа нет необходимости, если ваш переезд временный или связан с проблемами старого доменного имени. При получении бана или фильтра вы перенесете прошлые проблемы на новый адрес.
В чем разница между постоянной и другими переадресациями?
302 и 301 редирект похожи между собой. Тем не менее для большинства случаев оптимальным решением станет именно постоянная переадресация.
Эти коды ответа HTTP не одинаково воспринимаются роботами и, соответственно, по-разному влияют на поисковую выдачу. Редирект 301 — знак того, что поисковику стоит забыть о старом адресе и больше никогда на него не заходить. А 302 дает сигнал о продолжении индексирования контента, размещенного на изначально запрашиваемой странице.
В случае 301 перенаправления утратившая актуальность публикация перестанет отображаться в поисковой выдаче. При 302 редиректе в индексе будут присутствовать обе страницы.
По сути, лучше всегда ставить код 301.
Временное перенаправление рекомендовано лишь в исключительных случаях, когда:
- на запрашиваемой странице есть ссылки, которые обязаны и дальше индексироваться;
- индексация новой страницы не является критичной.
Опыт из практики: 301 редирект против 302
Статус 302 — временная мера, сообщающая поисковикам о том, что на старой странице проходят технические работы и ее надо сохранить в выдаче.
Рассмотрим на примере. Сайт изменил доменную зону, а затем еще и обзавелся защищенным протоколом https. Однако разработчики настроили не постоянное, а временное перенаправление.
Итог:
Во время работы 302 редиректа в индексе Google находилось 3 копии одной и той же интернет-площадки. Из-за этого произошло существенное проседание позиций.
Когда ошибка была исправлена, роботы склеили дубли, исключив лишние страницы из своей выдачи. Сайт снова вернулся в ТОП.
301 редирект vs Canonical
Несмотря на определенные нюансы, поисковые системы установили четкие правила использования команд. Вот как их понимает Гугл:
- 301 — «Моя страница навсегда переехала в другое место, она не вернется. Удалите, пожалуйста, ее из своего индекса и передайте вес новому документу».
- Canonical — «У меня имеется несколько версий содержания страницы. Просканируйте, пожалуйста, приоритетную для меня копию, которую я пометил canonical. Остальные материалы тоже будут доступны пользователям, но индексировать их не нужно».
Когда лучше применить 301 редирект:
- это лучший метод по умолчанию;
- для ошибки 404 и контента, утратившего актуальность, но имеющего
- внешние ссылки и много трафика;
- при смене домена в результате ребрендинга или продажи ресурса;
- для страницы, которая переехала навсегда.
Случаи использования rel=«canonical»:
- если статья имеет нужные посетителям дубли, например, описания
- одной и той же продукции, но разного цвета;
- когда постоянное перенаправление реализовать трудно;
- для кросс-доменов с похожими статьями;
- при разных адресах одного контента (сортировка каталога).
Где настраивается 301 редирект?
В зависимости от движка, переадресацию можно выполнить разными способами.
.htaccess, или httpd.conf для Apache
Это популярный благодаря своей простоте метод, для осуществления которого надо создать файл под названием .htaccess в папке сайта. Или отредактировать, если он уже предусмотрен движком.
Важно! Перед любыми изменениями сделайте Backup редактируемого файла (или всего сайта)
Для постоянного перенаправления пропишите в начало файла, подставив свои данные:
- Редирект всего сайта на другой адрес:
- Редирект с одной страницы на другую:
- Редирект с www на без www:
RewriteCond %{HTTP_HOST} ^www.example.ru [NC]
RewriteRule ^(.*)$ https://example.ru/$1 [R=301,L]
- Переадресация с HTTP на HTTPS
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
Учтите, что при работе с файлом команда происходит на уровне сервера с ОС Linux или Apache с активированным модулем Mod_rewrite.
Вы можете изменить .htaccess редирект конфигурационным файлом hpptd.conf. В таком случае удастся создать меньшую нагрузку на сервер, однако у веб-мастеров обычно нет к нему доступа.
Через плагины в CMS
Редирект на другой сайт легко настроить при помощи специального плагина. Так, для WordPress подойдет расширение Simple 301 Redirects. Единственный недостаток дополнительного модуля — ручное формирование списка адресов для переадресации.
Через PHP-условие
Такое решение подойдет тем, кто отлично знает структуру web-проекта и разбирается в PHP. Если сайт сделан на CMS, попробуйте открыть файл index.php в корне движка и прописать там:
if($_SERVER['REQUEST_URI'] == "/index.php") {
header("Location: /",TRUE,301);
exit();
}
(в первой строке укажите старый url, а во второй — новый)
Кроме того, перенаправление PHP можно сделать при помощи отправки заголовков (скрипта):
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.newdomain.ru/newdir/newpage.htm");
exit();
?>
ASP редирект
<%@ Language=VBScript %>
<%
Response.Status="301 Moved Permanently"
Response.AddHeader "Location", "https://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","https://www.new-url.com");
}
</script>
ColdFusion редирект
<.cfheader name="Location" value="https://www.new-url.com">
JSP (Java) редирект
Представленный способ подойдет для небольшой корректировки простых проектов. Код можно прописать лишь в одном файле, а сам файл добавить на все нужные страницы, указав:
<script type="text/javascript" src="redirect.js"></script>
<script type="text/javascript">
location="https://google.com";
</script>
(перенаправление на другой сайт)
CGI-скрипт на PERL
print $q->redirect("https://www.new-url.com/");
Ruby on Rails
headers["Status"] = "301 Moved Permanently"
redirect_to "https://www.new-url.com/"
end
Редирект в nginx
if ($host = 'www.domain.com' ) {
rewrite ^(.*)$ https://domain.com$1 permanent;
}
HTML-редирект
Если у вас простой статический сайт и требуется изменить лишь одну страницу, сделайте редирект HTML. Для этого необходимо добавить специальный мета-тег внутри.
Вот пример использования редиректа на другой ресурс после 5-секундной задержки:
Если поставить значение
вместо
, то читатель отправится на
моментально.
Однако для больших сайтов HTML-перенаправление делать сложно и затратно по времени, поэтому лучше отдать предпочтение другому варианту.
Редиректы по типам задачи
Пора избавиться от копий для улучшения позиций в поисковой выдаче!
Перенаправление с www / без www
Для настройки главного зеркала добавьте в файл .htaccess строки:
RewriteRule ^(.*)$ https://%1/$1 [L,R=301]
Также редирект с www можно выполнить благодаря синтаксису:
RewriteCond %{HTTP_HOST} ^www.site.ru$ [NC]
RewriteCond %{REQUEST_URI} !^/robots.*
RewriteRule ^(.*)$ https://site.ru/$1 [R=301,L]
Массовая склейка index.php, index.html, index.htm, index.asp
RewriteRule ^(.*)index.(php|html|htm)$ https://site.ru/$1 [R=301,L]
Редирект с http и https
При переезде на защищенный протокол, следует добавить:
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
или
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Редирект с https на http
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
Склейка дублей со слешем в конце url
Для удаления слеша по всему сайту используйте код:
RewriteCond %{REQUEST_URI} !&
RewriteCond %{REQUEST_URI} !=
RewriteCond %{REQUEST_URI} !.
RewriteCond %{REQUEST_URI} ![^/]$
RewriteRule ^(.*)/$ /$1 [R=301,L]
Чтобы сделать редирект со страниц без слеша на слеш, добавьте:
RewriteCond %{REQUEST_URI} !&
RewriteCond %{REQUEST_URI} !=
RewriteCond %{REQUEST_URI} !.
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.*[^/])$ /$1/ [R=301,L]
Как удалить несколько слешей или тире в адресной строке?
В случае с лишними слешами в url, необходимо сделать перенаправление на страницу с одним слешем:
RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]
Для склейки тире воедино пропишите от
:
RewriteRule . %1-%2 [R=301,L]
Совет! Чтобы упростить процесс, новичкам лучше воспользоваться услугами сервисов по генерации редиректов. Подставив свои данные, вы моментально получите готовый код:
https://www.webconfs.com/htaccess-redirect-generator.php
https://www.rapidtables.com/web/tools/redirect-generator.htm
Редирект одного url на другой адрес
Самой быстрой переадресацией страницы на новый адрес является:
Готовы найти решения для не шаблонных случаев? Тогда читайте дальше!
С сохранением GET-параметров
— url до параметра
— значение после параметра (вместо ?= ставится ^)
— новый адрес.
Когда некоторые GET-параметры не заданы или имеют произвольное значение, выбирайте следующий синтаксис:
RewriteRule ^dir/index.php$ /new/sef/? [R=301,L]
Без сохранения GET-параметров
Для переадресации адреса site.ru/index.php на основное зеркало site.ru:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /index.php HTTP/
RewriteRule ^index.php$ https://www.site.ru/ [R=301,L]
или
RewriteCond %{QUERY_STRING} ^z
RewriteRule ^(.*)$ https://site.ru/? [R=301,L]
На url с нижним регистром
Опытные разработчики знают, что поисковые системы отличают разный регистр букв, поэтому еще на начальном этапе стараются добавлять все адреса именно в нижнем регистре. Если вы упустили из внимания этот момент, примените специальный алгоритм перенаправления.
Хотите знать, как сделать редирект с любого адреса на url в нижнем регистре? Пропишите следующий код на уровне php-скрипта:
$lowerURI=strtolower($_SERVER['REQUEST_URI']);
if($_SERVER['REQUEST_URI']!=$lowerURI)
{
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://" . $_SERVER['HTTP_HOST'] . $lowerURI);
exit();
}
С внутренней страницы на главную
RewriteCond %{HTTP_HOST} ^www.site.ru$ [NC]
RewriteRule ^vnutrenyaya-stranica/$ https://www.site.ru/ [R=301,L]
Редирект каталога
В случае изменения структуры каталога, отображаемой в url:
Если же адрес устаревшего каталога идет сразу после названия сайта (
), используйте синтаксис:
Примечание! Эти варианты обычно подходят для решения глобальных задач, но из-за особенностей отдельных движков они могут нуждаться в доработке.
Редирект при изменении файловых расширений
Если переезд на другую систему управления контентом или платформу привел к изменению расширений файлов, вам понадобится такой код:
Как склеить домены или переехать на другой сайт?
Рассмотрим все возможные сценарии.
Со всех страниц одного домена на главную другого домена
Добавьте в файл .htaccess сайта с которого делаете редирект следующие строки:
RewriteRule ^(.*)$ https://site.ru/ [L,R=301]
(site.ru — площадка, на которую будет вести редирект)
С внутренних страниц на главную
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule !(^$|.*.(css|jpg|gif)) / [R=301,L]
С главной страницы на внутреннюю
RewriteCond %{HTTP_HOST} ^www.site.ru$ [NC]
RewriteRule ^$ https://www.site.ru/vnutrenyaya-stranica/ [R=301,L]
С поддомена на основной домен
RewriteRule ^(.*)$ https://site.ru%{REQUEST_URI} [R=301,NC,L,QSA]
Со страниц одного домена на аналоги в другом
RewriteRule ^(.*)$ https://site.ru/$1 [L,R=301]
Когда редирект на другой сайт нужен при смене структуры url, должен помочь код:
RewriteRule ^category/([^/]+)/?$ $1 [L]
Если синтаксис не решил проблему, обратитесь к разработчикам ресурса — они доработают предложенные выше варианты в соответствии с особенностями вашей CMS. Учтите также, что в данном случае необходимо составить карту редиректов.
Переадресация для кириллических доменов
Доменные имена в зоне .рф подчиняются тем же правилам, однако вы должны все русские буквы заменить альтернативным кодом:
RewriteRule ^(.*)$ https://www.site.ru/$1 [R=301,L]
(где
— это зона
, а
— адрес старого сайта)
Другие полезные настройки .htaccess
Редирект 301 может пригодиться в разных ситуациях.
Указание пути к файлу 404 ошибки
Путь к файлу указывается внедрением синтаксиса:
Учтите, что все правила обязаны выполняться в прямой очередности их нахождения в .htaccess.
Альтернативный вариант на PHP:
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.site.ru/dir/");
exit();
?>
Настройка 403 кода ответа сервера для списка ресурсов с реф-спамом
301-редирект для спама по REFERER осуществляется так:
RewriteCond %{HTTP_REFERER} another-ref-spam.ru [NC]
RewriteRule .* - [F]
Это позволит вам отклонить реферальный спамный трафик по заголовку HTTP_REFERER с ряда сайтов.
Настройка редиректа лишь для некоторых USER_AGENT’ов, а не для всех пользователей
RewriteRule (.*) https://mobile.site.ru/ [L,R=301]
Если надо поставить редирект для всех поисковых роботов (представлен список их USER_AGENT’ов)
RewriteRule (.*) https://no-search.site.ru/ [L,R=301]
Синтаксис для регулярных выражений в .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] | аналогично. |
Как проверить 301 редирект?
Существует два вида корректной проверки внесенных изменений:
- поштучно вручную через сервисы bertal.ru или Header Checker Tool;
- пачкой с помощью программы Screaming Frog Seo Spider, способной просканировать весь сайт.
Внимание! Поисковым системам требуется время, чтобы обнаружить код 301 и присвоить вес новой странице. Длительность процедуры зависит от того, как часто роботы посещают этот адрес (может пройти до 2-3 недель).
Ошибки при использовании редиректов
- использование внутренних перенаправлений без изменения url в ссылках;
- внедрение многошагового редиректа;
- установка временной переадресации вместо постоянной;
- неправильный выбор типа редиректа;
- перенаправление файла robots.txt;
- непонимание разницы между
rel=canonical
и кодом 301;
- редирект на нерелевантный контент;
- переадресация, которая не приводит к 200-й странице.
Сохраните руководство в закладки, чтобы всегда иметь под рукой. Оно точно вам еще пригодится!