htaccess redirect www to non www
Every developer has a
tab open to
Stack Overflow
A public platform building the definitive collection of coding questions & answers
A community-based space to find and contribute answers to technical challenges, and one of the most popular websites in the world.
A private collaboration & knowledge sharing SaaS platform for companies
A web-based platform to increase productivity, decrease cycle times, accelerate time to market, and protect institutional knowledge.
Thousands of organizations around the globe use Stack Overflow for Teams
Capture your company’s knowledge and context in a discoverable format to unblock your team
Increase productivity
If somebody somewhere has the right answer, suddenly you have it too. Collaborate better in a remote-first world.
Accelerate time to market
Shorten the time between initial idea and complete product. Take delays and misinformation out of the equation.
Protect institutional knowledge
People come and people go, but if you capture their contributions in one central place, that expertise sticks around.
Ensure your company stays on course
Here are just a few types of technologists that we help.
DevOps engineers
Shipping new products and features requires teamwork and coordination. Forget checklists and long docs no one ever reads.
Data scientists
Business decisions are better when backed by data. Give visibility to the data that support your strategies.
Software engineers
Help engineers be more efficient and streamline knowledge sharing using a tool they already love and trust.
Support teams
Level up your support by providing information to your customers using a natural interface: questions and answers.
Engineering leaders
Free knowledge sharing and collaboration platform
Always free up to 50 teammates
Basic
Centralized knowledge and collaboration platform for small and growing teams
Up to 250 teammates
Business
For small and medium sized businesses seeking advanced administrative tools
Enterprise
For medium to large businesses with additional security, configurability and content management needs
Integrates with and improves other tools
All plans come with integrations for ChatOps tools Slack & Microsoft Teams in order to cut down on pings, limit distractions and make the tools even more powerful. Business and Enterprise customers get access to Jira, GitHub & Okta integrations.
Robust read and write API
Single sign-on with AD or SAML
Your own customer success representative
99.5% uptime SLA and priority support
Stack Overflow for Teams has been a resource for our entire company. Not only for developers to solve problems, it’s also enabled our sales field to answer technical questions that help them close deals.
Engineers should help solve the hardest questions, the unknowns, where being familiar with how the product was built is essential. But we don’t want to keep answering solved problems over and over again. That’s where Stack Overflow for Teams really helps.
As we started to use [Stack Overflow for Teams] and saw how nice it was to have a repository of information, we started to see it spread to other teams. Our customer support team started using it, our people success team started using it, next thing we knew, we had [Slack] integrations all over the place.
What we love about Stack Overflow for Teams is that it’s a very dynamic tool…there’s just so many ways to use this as a liaison between different teams and different knowledge bases.
Additional products that reach and engage developers & technologists…
Reach the world’s largest audience of developers and technologists
Connecting communities with the specific technologies they use the most
Build your employer brand to attract tech talent
Programming & related technical career opportunities
Explore technical topics and other disciplines across 170+ Q&A communities
From Server Fault to Super User, much of the Stack Exchange network continues our mission to empower the world to develop technology through collective knowledge. Other sites on the Stack Exchange network further encourage knowledge sharing across topics such as cooking and medicine.
Build a private community to share technical or non-technical knowledge.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40232
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
.htaccess redirect www to non-www with SSL/HTTPS
I need to force a https prefix on every domain while also ensuring www versions redirect to no-www ones.
Below is my code; it doesn’t work:
What am I doing wrong and how can I achieve it?
9 Answers 9
www to non www with https
If instead of example.com you want the default URL to be www.example.com, then simply change the third and the fifth lines:
Your condition will never be true, because its like «if (a == a + b)».
I’d try the following:
To enforce non-www and https in a single request, you can use the following Rule in your htaccess :
This works for me perfectly!
Certificate must cover both www and non-www https. Some provider’s certs cover both for www.xxxx.yyy, but only one for xxxx.yyy.
Make all http use https:
Make only www https use the non-www https:
Cannot be processing non-www https, otherwise a loop occurs.
More generic
to make any url with www drop it.
to force any non-https url, even for those system downstream from load-balancers that drop https, use https.
Note that I have not tested the forwarded options, so would appreciate feedback on any issues with them. Those lines could be left out if your system is not behind a load-balancer.
TO HTTP_HOST or not
Specifying the domain name explicitly ensures that no slight-of-hand character-bending means are used in the user-supplied URL to possibly trick your site into doing something it might not be prepared for, or at least ensures that the proper domain name appears in the address bar, regardless of which URL string opened the page.
It might even help convert punycode-encoded domains to show the proper unicode characters in the address bar.
Every developer has a
tab open to
Stack Overflow
A public platform building the definitive collection of coding questions & answers
A community-based space to find and contribute answers to technical challenges, and one of the most popular websites in the world.
A private collaboration & knowledge sharing SaaS platform for companies
A web-based platform to increase productivity, decrease cycle times, accelerate time to market, and protect institutional knowledge.
Thousands of organizations around the globe use Stack Overflow for Teams
Capture your company’s knowledge and context in a discoverable format to unblock your team
Increase productivity
If somebody somewhere has the right answer, suddenly you have it too. Collaborate better in a remote-first world.
Accelerate time to market
Shorten the time between initial idea and complete product. Take delays and misinformation out of the equation.
Protect institutional knowledge
People come and people go, but if you capture their contributions in one central place, that expertise sticks around.
Ensure your company stays on course
Here are just a few types of technologists that we help.
DevOps engineers
Shipping new products and features requires teamwork and coordination. Forget checklists and long docs no one ever reads.
Data scientists
Business decisions are better when backed by data. Give visibility to the data that support your strategies.
Software engineers
Help engineers be more efficient and streamline knowledge sharing using a tool they already love and trust.
Support teams
Level up your support by providing information to your customers using a natural interface: questions and answers.
Engineering leaders
Free knowledge sharing and collaboration platform
Always free up to 50 teammates
Basic
Centralized knowledge and collaboration platform for small and growing teams
Up to 250 teammates
Business
For small and medium sized businesses seeking advanced administrative tools
Enterprise
For medium to large businesses with additional security, configurability and content management needs
Integrates with and improves other tools
All plans come with integrations for ChatOps tools Slack & Microsoft Teams in order to cut down on pings, limit distractions and make the tools even more powerful. Business and Enterprise customers get access to Jira, GitHub & Okta integrations.
Robust read and write API
Single sign-on with AD or SAML
Your own customer success representative
99.5% uptime SLA and priority support
Stack Overflow for Teams has been a resource for our entire company. Not only for developers to solve problems, it’s also enabled our sales field to answer technical questions that help them close deals.
Engineers should help solve the hardest questions, the unknowns, where being familiar with how the product was built is essential. But we don’t want to keep answering solved problems over and over again. That’s where Stack Overflow for Teams really helps.
As we started to use [Stack Overflow for Teams] and saw how nice it was to have a repository of information, we started to see it spread to other teams. Our customer support team started using it, our people success team started using it, next thing we knew, we had [Slack] integrations all over the place.
What we love about Stack Overflow for Teams is that it’s a very dynamic tool…there’s just so many ways to use this as a liaison between different teams and different knowledge bases.
Additional products that reach and engage developers & technologists…
Reach the world’s largest audience of developers and technologists
Connecting communities with the specific technologies they use the most
Build your employer brand to attract tech talent
Programming & related technical career opportunities
Explore technical topics and other disciplines across 170+ Q&A communities
From Server Fault to Super User, much of the Stack Exchange network continues our mission to empower the world to develop technology through collective knowledge. Other sites on the Stack Exchange network further encourage knowledge sharing across topics such as cooking and medicine.
Build a private community to share technical or non-technical knowledge.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40232
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Редирект домена с www на без www на Apache в Ubuntu 14.04
Когда сайт или приложение запущены на домене, часто возникает необходимость позволить пользователям открывать его при помощи простого домена и поддомена www. То есть, пользователи должны иметь возможность посетить домен и с префиксом www, и без него (например: example.com или www.example.com), и при этом получить доступ к одному и тому же контенту. Существует множество способов решения этой проблемы. Лучше всего заранее определиться, какой домен вам подходит больше (с префиксом или без), а затем настроить переадресацию второго домена на основной. Такой редирект называется постоянным (Permanent Redirect), или 301. Его настройки содержатся в конфигурациях DNS и веб-сервера.
Это руководство покажет, как настроить редирект URL-а с префиксом www на URL без префикса на веб-сервере Apache в системе Ubuntu 14.04 (например, с www.example.com на example.com).
Примечание: Аналогичную статью для CentOS 7 можно найти по этой ссылке. Чтобы настроить такую переадресацию на веб-сервере Nginx в Ubuntu, читайте данную статью.
Требования
Для выполнения инструкций нужны права суперпользователя (sudo или root). Подробнее об этом можно узнать в статье «Начальная настройка сервера Ubuntu 14.04».
Кроме того, нужно предварительно установить Apache. Полезные статьи по установке и настройке этого веб-сервера можно найти в специальном разделе данного сайта.
Также нужно иметь возможность добавлять DNS-записи.
Настройка DNS-записи
Чтобы настроить редирект с www.example.com на example.com (или наоборот), нужно создать запись для каждого имени.
Откройте панель управления DNS.
Если записи домена ещё не существует, создайте её сейчас. В hostname укажите доменное имя (к примеру, example.com), в поле IP address нужно указать внешний IP-адрес сервера Apache. Некоторые системы создают запись A, которая указывает на заданный IP-адрес, автоматически, а некоторые требуют создавать эти записи вручную.
Затем создайте еще одну запись А, на этот раз для адреса с префиксом www, указав тот же IP-адрес.
Примечание: Такой редирект работает и с записями CNAME, поскольку запись А канонического имени привязана к IP-адресу веб-сервера Apache.
Теперь сервер доступен по двум доменам: с префиксом www и без него. Можно начинать настройку редиректа.
Включение модуля mod_rewrite
Для настройки редиректа 301 в Apache используется модуль mod_rewrite, который позволяет переадресовывать пользователей на любой необходимый домен (в том числе и на домен без префикса www).
Чтобы включить модуль, используйте команду:
sudo a2enmod rewrite
Теперь можно приступать к настройке редиректа Apache.
sudo vi /etc/apache2/sites-enabled/000-default.conf
Найдите DocumentRoot сайта и запишите его (по умолчанию это каталог /var/www/html).
Затем добавьте в файл директиву Directory, указав DocumentRoot:
Add to Apache configuration
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
Сохраните и закройте файл.
sudo service apache2 restart
Настройка модуля Rewrite
Этот файл будет пуст (если только он не был создан предварительно). Выберите направление редиректа и следуйте инструкциям соответствующего раздела.
1: Редирект с www на без www
Чтобы настроить редирект пользователей с домена с префиксом www на домен без него, внесите следующий код:
htaccess — www to non-www
RewriteEngine On
RewriteBase /
RewriteCond %
Сохраните и закройте файл. Изменения немедленно вступят в силу. Обратите внимание: при использовании HTTPS необходимо заменить http в строке RewriteRule на https.
Затем используйте следующую команду curl, чтобы убедиться, что редирект настроен верно (не забудьте указать свой домен):
На экране должен появиться вывод, сообщающий о точке переадресации:
HTTP/1.1 301 Moved Permanently
Date: Fri, 01 May 2015 21:18:33 GMT
Server: Apache/2.4.7 (Ubuntu)
Location: http://example.com/
Content-Type: text/html; charset=iso-8859-1
После этого нужно проверить переадресацию при помощи браузера.
2: Редирект домена без www на домен с www
Чтобы настроить переадресацию пользователей с обычного домена без префикса www на домен с www, добавьте в файл:
.htaccess — non-www to www
RewriteEngine On
RewriteBase /
RewriteCond %
Сохраните и закройте файл, после чего изменения будут активированы. При использовании HTTPS не забудьте заменить http в строке RewriteRule на https.
Затем используйте следующую команду curl, чтобы убедиться, что редирект настроен верно (не забудьте указать свой домен):
На экране появится сообщение, которое показывает, что точкой редиректа является домен с префиксом:
HTTP/1.1 301 Moved Permanently
Date: Fri, 01 May 2015 21:18:33 GMT
Server: Apache/2.4.7 (Ubuntu)
Location: http://www.example.com/
Content-Type: text/html; charset=iso-8859-1
Конечно, после этого необходимо также проверить редирект в браузере.
Заключение
Как видите, настроить редирект на сервере Apache довольно просто. Теперь сайт доступен по двум доменам: с префиксом и без.
Чтобы получить более подробную информацию о mod_rewrite, читайте руководство «Настройка Mod_Rewrite».
На хостинге RU-CENTER в настоящее время используется веб-сервер Apache версии 2.4.
Директивы файла .htaccess действуют для каталога, в котором размещён такой файл, и для всех его подкаталогов. Если вы желаете с помощью .htaccess изменить настройки для сайта в целом, его следует размещать в корневом каталоге сайта
Пожалуйста, будьте внимательны при редактировании файла .htaccess! При сохранении такого файла в кодировке UTF-8 в нём не должно присутствовать BOM-сигнатуры. Для редактирования файла .htaccess и других конфигурационных файлов мы рекомендуем использовать не «Блокнот» Windows, а специальные текстовые редакторы, например Notepad++.
1. Перенаправление доменов c синонима сайта на основной домен с кодом 301
Перенаправить запросы на domain.ru с любого из синонимов сайта
RewriteEngine On
RewriteCond %
RewriteRule ^(.*)$ http://domain.ru/$1 [L,R=301]
Перенаправить запросы на www.domain.ru с любого из синонимов сайта
RewriteEngine On
RewriteCond %
RewriteRule ^(.*)$ http://www.domain.ru/$1 [L,R=301]
Эти правила рекомендуется размещать в самом начале файла .htaccess.
2. Постоянное перенаправление с кодом 301
Redirect 301 /page.html http://www.domain.ru/new_page.html
Например, для перенаправления всех запросов к странице /period/?test=123 вашего сайта на domain.ru, вы можете написать:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %
RewriteRule ^period/$ http://domain.ru/ [L,R=301]
3. Переопределение страниц ошибок
#401 Авторизация не выполнена
ErrorDocument 401 http://domain.ru/errors/401.html
#403 Доступ запрещен
ErrorDocument 403 http://domain.ru/errors/403.html
#404 Страница не найдена
ErrorDocument 404 http://domain.ru/errors/404.html
#500 Внутренняя ошибка сервера
ErrorDocument 500 http://domain.ru/errors/500.html
Соответствующие файлы страниц ошибок (401.html, 404.html и др.) необходимо разместить в каталоге
Для того чтобы при случайном упоминании прямых ссылок на такие страницы они не проиндексировались в поисковых системах, рекомендуется:
User-agent: *
Disallow: /errors
/ваш_домен/docs/errors/.htaccess, в котором прописать
4. Постраничное перенаправление запросов на другой домен c кодом 301
Следующий код перенаправит все запросы к страницам вашего сайта на аналогичные страницы другого сайта, например, запрос http://domain.ru/main будет переадресован на http://www.newdomain.ru/main:
Redirect 301 / http://www.newdomain.ru/
RewriteEngine On
RewriteRule ^(.*)$ http://newdomain.ru/$1 [R=301,L]
5. Ограничение доступа к сайту по IP
Запретить доступ к сайту с IP-адресов 123.4.5.6 и 123.5.4.3
Order Allow,Deny
Allow from all
Deny from 123.4.5.6 123.5.4.3
Запретить доступ к сайту со всех адресов кроме 123.4.5.6 и 123.5.4.3:
Order Deny,Allow
Deny from all
Allow from 123.4.5.6 123.5.4.3
Запретить доступ к сайту для всех:
6. Переопределение главной страницы сайта (индексного файла каталога)
Сделать главной страницей файл menu.html:
8. Запрет выдачи листинга каталога
В случае отсутствия в папке главной страницы (индексного файла), при обращении без указания конкретного имени файла в запросе будет выдан список всех файлов, находящихся в каталоге. Для того чтобы запретить отображение листинга каталога, добавьте в файл .htaccess строку:
Скрипт должен иметь атрибут исполнения (+x, права доступа, начинающиеся с 7, например, 755).
10. Блокировка переходов со сторонних ресурсов
Для запрета перехода c baddomain.ru на domain.ru добавьте в .htaccess следующее:
Если требуется запретить переходы с нескольких доменов, то используйте следующие директивы
В файле .htaccess использование кириллицы не допускается. При составлении правил перенаправления для кириллических доменов необходимо указывать имя домена в punycode. Узнать имя домена в punycode можно с помощью сервиса Whois.
Например, для перенаправления site.ru на caйт.рф нужно воспользоваться следующим правилом:
RewriteEngine on
RewriteCond %
RewriteRule ^(.*)$ http://xn--80aswg.xn--p1ai/$1 [R=301,L]
В этом случае ваши посетители могут увидеть именно punycode-представление доменного имени в адресной строке браузера. Это не является ошибкой.
12. Перенаправление с HTTP на HTTPS и обратно
Для работы перенаправления на сайте должен быть установлен действительный SSL-сертификат.
Перенаправить запросы на https://domain.ru
Перенаправить запросы на http://domain.ru
3. Диагностика ошибок
Если после редактирования или размещения .htaccess при обращении к сайту вы получили ошибку 500, то, скорее всего, в файле .htaccess допущена ошибка. Посмотреть её причины вы можете в лог-файле /var/log/ваш_домен.error_log.