apache redirect www to non www

How to Redirect www to non-www in Apache htaccess

Sometimes you may need to redirect www URLs to non-www URLs for your website for SEO benefits. Here’s how to redirect www to non-www in Apache htaccess. You can use these steps to ensure that there is only one version (non-www) of your website available online.

How to Redirect www to non-www in Apache htaccess

Here are the steps to redirect www to non-www in Apache htaccess file. Please ensure that you have enabled mod_rewrite in your Apache web server configuration. Only then your htaccess configuration will be applied by Apache server.

If you have enabled htaccess using mod_rewrite, you can skip to step 4.

1. Enable mod_rewrite

Open terminal and run the following command to enable mod_rewrite on Ubuntu/Debian systems. It is already enabled in CentOS/Redhat systems.

If mod_rewrite is already enabled, you will see an alert message.

Restart Apache web server

Add the following lines just before line.

Restart Apache web server

4. Redirect www to non-www in Apache htaccess

Let’s say you want to redirect all URLs from www.example.com to example.com

Add the following lines in your htaccess file.

In the above lines the RewriteCond directive checks HTTP_HOST value of every request. If it begins with www.example.com, then RewriteRule directive permanently redirects it to example.com along with original URL string. If you want to redirect only temporarily, use R=302 above, instead of R=301.

5. Restart Apache Server

Restart Apache web server

Now your Apache web server will automatically redirect www URLs to non-www URLs.

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!

Источник

Apache redirect www to non-www and HTTP to HTTPS

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:

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

Apache Configuration

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.

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.

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).

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

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

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

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:

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.

Related Posts

Filed under: Softwares Internet — About: servers Apache htaccess redirects HTTPS

Читайте также:  программа обучения по охране труда для руководителей и специалистов 2021 в школе

Источник

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.40224

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How To Redirect www to Non-www with Apache on Ubuntu 14.04

Published on May 4, 2015

Читайте также:  Что только не представилось мне за это время

Introduction

If you want to perform this type of redirect with Nginx as your web server, you should follow this tutorial instead: How to Redirect www to non-www with Nginx on Ubuntu 14.04.

Prerequisites

This tutorial assumes that you have superuser privileges, i.e. sudo or root, on the server that is running Apache. If you don’t already have that set up, follow this tutorial: Initial Server Setup on Ubuntu 14.04.

It is assumed that you have Apache installed. If you do not already have this set up, there are several tutorials on the subject under the Apache tag.

You must be able to add records to the DNS that is managing your domain. If you do not already have a domain, you may purchase one from a domain registrar, and manage it with the registrar’s DNS or DigitalOcean’s DNS. In this tutorial, we will use the DigitalOcean DNS to create the necessary records.

Let’s get started by configuring your DNS records.

Configure DNS Records

In order to set up the desired redirect, www.example.com to example.com or vice versa, you must have an A record for each name.

Open whatever you use to manage your DNS. For our example, we’ll use the DigitalOcean DNS.

Next, add another A record with “www” as the hostname (or “www.example.com” if the partial subdomain doesn’t work), and specify the same IP address.

When you have created both records, it should look something like this:

Note: This will also work with CNAME records, as long as the canonical name’s A record refers to the IP address of your Apache web server.

Now your server should be accessible via the www and non-www domain, but we still need to set up the redirect. We’ll do that now.

Enable Rewrite Module

In order to perform the 301 redirect, we will use the Apache mod_rewrite, or Rewrite, module. Doing so will ensure that your users can access your site with or without the www. prefix, and be redirected to the domain that you prefer.

First, enable the mod_rewrite module with this command:

Add the following Directory directive to the configuration and be sure to substitute the DocumentRoot for the highlighted part:

Now restart Apache to put the change into effect:

Configure Rewrite Module

Change directories to your DocumentRoot, in our case, /var/www/html :

Of course, if you haven’t created the file before, it will be blank. Depending on which direction you want to redirect, use one of the following options.

Option 1: Redirect www to non-www

If you want redirect users from www to a plain, non-www domain, insert this configuration:

Save and exit. The changes should go into effect immediately. Note that if you are using HTTPS, you should update “http”, in the RewriteRule line, to “https”.

Use this curl command to ensure that the non-www domain redirects to the www domain (replace the highlighted part with your actual domain):

You should get a 301 Moved Permanently response, that shows the non-www redirect location, like this:

Of course, you should access your domain in a web browser (www and non-www) to be sure.

Option 2: Redirect non-www to www

If you want redirect users from a plain, non-www domain to a www domain, insert this configuration:

Save and exit. the changes should go into effect immediately. Note that if you are using HTTPS, you should update “http”, in the RewriteRule line, to “https”.

Use this curl command to ensure that the non-www domain redirects to the www domain (replace the highlighted part with your actual domain):

You should get a 301 Moved Permanently response, that shows the www redirect location, like this:

Of course, you should access your domain in a web browser (www and non-www) to be sure.

Conclusion

That’s it! Your Apache redirect is now configured properly, and your users will be able to access your web server via your non-www and www domain.

If you would like to understand more about mod_rewrite, the Apache feature that we used to implement the redirect, feel free to read this tutorial: How To Set Up Mod_Rewrite.

Software Engineer @ DigitalOcean. Former Señor Technical Writer (I no longer update articles or respond to comments).

Источник

Редирект домена с 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 % ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Сохраните и закройте файл. Изменения немедленно вступят в силу. Обратите внимание: при использовании 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 % !^www\. [NC] RewriteRule ^(.*)$ http://www.%/$1 [R=301,L]

Сохраните и закройте файл, после чего изменения будут активированы. При использовании 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».

Источник

Образовательный портал