Как добавить или удалить префикс WWW к доменному имени

Автоматическое добавление префикса "www" к доменному имени.

Для перенаправления (например) example.com в www.example.com, необходимо добавить следующие строки в .htaccess.

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

Если у вас много доменов example.info, example.gr ..., и вы хотите их перенаправить на www.example.com, пишем следующие строки в .htaccess:

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

This second set of rules checks to see if the URL has a domain name portion of www.example.com. If it doesn't, the visitor is redirected to www.example.com. In other words, any web address with a domain name component other than www.example.com will cause a redirection to take place.

Whichever set of rules you use, change all instances of "example.com" to your actual domain name. For the line beginning with RewriteCond, add a backslash ("\") before each of the full stops (or "periods") in your domain name.

Note that the second set of rules has some side effects:

  • Some people park new domains they buy at their current site, pending the development of a new website. If you do so, anyone accessing those parked domains will be redirected to the domain you specify above (eg, www.example.com).
  • In the same way, you will no longer be able to access your site at its IP address without being redirected. This is probably not a big issue, but it's good to know.
  • Some web hosts allow you to host multiple domains and subdomains on the same web account, with those domains redirected to a subdirectory of your main domain. For example, if the files for your domain (say) eg-domain.com can also be accessed as example.com/eg-domain/, this paragraph probably applies to you. Such web hosts may use mod_rewrite to implement support for these additional domains or subdomains. If you then also use the second set of mod_rewrite rules on your URLs, you may get 404 File Not Found errors for URLs in your extra domains/subdomains, depending on the end result of the combined rules. In such cases, it may be safer to use the first set of rules instead, since it very specifically targets only a single domain name.

Для удаления префикса WWW из доменного имени ипользуя Apache's mod_rewrite

Для перенаправления URL (например) www.example.com в example.com, пишем следующий код в .htaccess файл.

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

The above rules checks if the domain name component in a URL contains www.example.com. If it does, the visitor is sent to example.com instead.

To use the rule, change all instances of "example.com" to your actual domain name. For the line beginning with RewriteCond, add a backslash ("\") before each of the full stops (or "periods") in your domain name.

Если Вы установили какое либо приложение не в корень httpdocs, а в его подкаталог (например, /httpdocs/site), то обращение к Вашему сайту в браузере придется выполнять, указывая этот подкаталог: www.mysite.ru/site. Для того, чтобы Вы могли обращаться к сайту не указывая этой директории, необходимо добавить в файл .htaccess корня сервера следующие строки:

Если Вы хотите чтобы в браузере для главной страницы не отображался подкаталог:

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule !^site(/?|/.+)$ /site%{REQUEST_URI} [L]

где site - это тот каталог, куда Вы уставили приложение.

Если Вы хотите, чтоб браузер отображал подкаталог с приложением то:

DirectoryIndex /site/index.php

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

RewriteRule (.+) $1.html [L]

Следующая директива при "срабатывании" возвращает редирект. В качестве замены всегда должна использоваться абсолютная ссылка:

Redirect /site http://www.mysite.ru/site2/index.php