Убираем www и перенаправляем на защищенный протокол в Apache

Мне кажется прошло время, когда приставка www была чем-то необходимым при создании сайта. Сейчас больше ценится лаконичность адреса, наличие шифрования (HTTPS) и единого домена для лучшей индексации (canonical).

В этой статье мы рассмотрим настройку веб-сервера Apache для того чтобы перенести пользователя на домен без или с приставкой www в защищенном режиме.

Вступление

Тут я покажу как настроить сайт, чтобы убрать www (или наоборот) и поменять HTTP на безопасный HTTPS, используя конфигурацию сервера Apache. Если быть точным, конфигурация перенаправит следующие адреса:

http://example.com
http://www.example.com
https://example.com

на

https://example.com

Я также покажу небольшое изменение, с помощью которого можно добавить www в адрес(если вы предпочитаете с www).

Конфигурация Apache

Чтобы переадресация работала, добавьте следующее в конфиг Apache, если у вас есть к нему доступ, или в .htaccess в корневой папке вашего сайта:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

Если вместо example.com вы хотите, чтобы адрес сайта был www.example.com, просто измените третью и пятую строчки:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]

Как это работает

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

RewriteEngine On

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

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]

Эти две строчки – условия переадресации, они используются, чтобы определить нужна ли переадресация. Так как в условиях используется ИЛИ [OR], при выполнении хотя бы одного условия, Apache запустит правило перезаписи(переадресацию).

Первое условие определяет использовался ли адрес без HTTPS шифрования. Второе условие определяет использовался ли адрес с www. Заметьте, что я использовал www\. , а не www. , так как \ делает из . точки просто точку( . точка имеет в конфигурации свою функцию, поэтому лучше её избегать).

RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]

Четвёртая строка раскладывает адрес на составляющие: www(если существует) и остаток адреса. Позже мы обратимся к этому при помощи %1 в правиле перезаписи.

Если вам известно имя хоста, то вы можете не использовать эту проверку(смотрите дальше).

RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]

Правило перезаписи – это основа переадресации. Этой строкой мы говорим Apache переадресовать любой запрос на новый адрес:

  • https://www.
  • %1: ссылка на остаток адреса (без www)
  • %{REQUEST_URI}: URI запроса, без имени хоста

Все эти токены соединяются вместе и получается финальный URI переадресации. И в конце мы добавляем 3 флага:

  • NE не избегать специальных символов
  • R=301 использовать HTTP 301 статус переадресации
  • L не обрабатывать другие правила и переадресовать немедленно

Заметки

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

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,NE,R=301]

Вывод

Эта статья позволяет настроить простую переадресацию www и HTTP( не HTTPS) запросов к каноническому домену сайта. Это очень полезно, чтобы избежать проблему повторений с поисковыми системами, а так же облегчает серфинг вашим пользователям.

Существует множество способов осуществить переадресацию в Apache, это всего лишь один, и он не раскрывает все возможности. Я надеюсь, что обьяснение в параграфе “Как это работает” поможет вам настроить его под свои нужды.[:en]The increasing adoption of HTTPS as the default connection protocol for websites has introduced a few new challenges to developers and system administrators, such as the need to consolidate a canonical domain by redirecting non-HTTP sites to HTTPS, in addition to redirecting www to non-www host name (or vice-versa).

Introduction

Here I show how to redirect a site from www to non-www (or viceversa) and from HTTP to HTTPS, using the Apache server configuration. To be more clear, the configuration will redirect the following host names:

http://example.com
http://www.example.com
https://example.com

to

https://example.com

I’ll also show a small change to redirect the non-www to the www version, if you prefer the www.

Apache Configuration

To configure the redirects, add the following redirect rule either to the Apache config file if you have access to it, or to the .htaccess in the root of your site:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

If instead of example.com you want the default URL to be www.example.com, then simply change the third and the fifth lines:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]

How it works

Since I’m not a huge fan of cut-and-paste tutorials, let’s try to understand how the configuration works. That would help you to make the necessary modifications, if needed.

RewriteEngine On

The first line enables the Apache runtime rewriting engine, required to perform the redirect. You may have already enabled it in a previous config in the same file. If that’s the case, you can skip that line.

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]

These two lines are are the redirect conditions, they are used to determine if the request should be redirected. Because the conditions are joined with an [OR], if any of those two conditions returns true, Apache will execute the rewrite rule (the redirect).

The first condition determines if the request is using a non-HTTPS URL. The second condition determines if the request is using the www URL. Notice that I used www\. and not www., because the pattern is a regular expression and the . dot has a special meaning here, hence it must be escaped.

RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]

The forth line is a convenient line I used to avoid referending the hostname directly in the URL. It matches the HOST of the incoming request, and decomposes it into www part (if any), and rest of the hostname. We’ll reference it later with %1 in the RewriteRule.

If you know the host name in advance, you may improve the rule by inlining the URL and skipping this condition (see later).

RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]

The RewriteRule is the heart of the redirect. With this line we tell Apache to redirect any request to a new URL, composed by:

  • https://www.
  • %1: the reference to the non-www part of the host
  • %{REQUEST_URI}: the URI of the request, without the hostname

All these tokens are joined together, and represents the final redirect URI. Finally, we append 3 flags:

  • NE to not escape special characters
  • R=301 to use the HTTP 301 redirect status
  • L to stop processing other rules, and redirect immediately

Remarks

As I’ve already mentioned, my example uses an extra RewriteCond line to extract the host name, and avoid to inline the hostname in the rule. If you feel this is a performance penalty for you, you can inline the host directly in the rule:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,NE,R=301]

Conclusion

This articles provides a simple configuration to redirect www and non-HTTPS requests to the canonical site domain. This is very useful to avoid content duplication issues with search engines, and offer an improved experience to your users.

If you search online there are dozens of ways to perform a redirect in Apache, this is just one of the possibilities and it may not cover all the possible cases. Hopefully, with the explanation in the How it works section you will be able to customize it to your needs.

ru_RURussian