dns redirect www to non www
Давайте уже разберемся в DNS

Внимательный читатель найдет на этой картинке IPv6
Люди часто озадачены доменами. Почему мой сайт не работает? Почему эта хрень поломана, ничего не помогает, я просто хочу, чтобы это работало! Обычно, вопрошающий или не знает про DNS, или не понимает фундаментальных идей. Для многих DNS — страшная и непонятная штука. Эта статья — попытка развеять такой страх. DNS — это просто, если понять несколько базовых концепций.
Что такое DNS
DNS расшифровывается как Domain Name System. Это глобальное распределенное хранилище ключей и значений. Сервера по всему миру могут предоставить вам значение по ключу, а если им неизвестен ключ, то они попросят помощи у другого сервера.
Базовые штуки
Давайте взглянем на маппинг между именем и адресом:
Здесь есть только одна интересная деталь: информация о самом запросе. Говорится, что мы запросили запись и получили ровно один ответ. Вот:
Оставшаяся часть ответа описывает сам ответ:
Как видите, при обычном DNS-запросе происходит куча всего. Каждый раз, когда вы открываете веб-страницу, браузер делает десятки таких запросов, в том числе для загрузки всех внешних ресурсов вроде картинок и скриптов. Каждый ресурс отвечает за минимум один новый DNS-запрос, и если бы DNS не был рассчитан на сильное кэширование, то трафика генерировалось бы очень много.
Корневые DNS-сервера обслуживаются различными компаниями и государствами по всему миру. Изначально их было мало, но интернет рос, и сейчас их 13 штук. Но у каждого из серверов есть десятки или сотни физических машин, которые прячутся за одним IP.
Другие типы
Что не так с CNAME
Запросы к другим серверам
Давайте представим, что конфигурация DNS испорчена. Вам кажется, что вы исправили проблему, но не хотите ждать когда обновится кэш чтобы удостовериться. С помощью dig можно сделать запрос к публичному DNS-серверу вместо своего дефолтного, вот так:
Типичные ситуации
Давайте рассмотрим типичные ситуации, знакомые многим веб-разработчикам.
Редирект домена на www
Этот IP принадлежит Namecheap’у, и там крутится маленький веб-сервер, который просто делает перенаправление на уровне HTTP на адрес http://www.iskettlemanstillopen.com :
CNAME для Heroku или Github
Wildcards
Заключение
Надеюсь, теперь у вас есть базовое понимание DNS. Все стандарты описаны в документах:
Есть еще пара интересных RFC, в том числе 4034, который описывает стандарт DNSSEC и 5321, который описывает взаимосвязь DNS и email. Их интересно почитать для общего развития.
How to redirect www to non-www within domains?
What setting to I have to put in DNS at DO for a domain, so that www.domain.com/whatever to be redirected to domain.com/whatever?
And what setting to put so that if someone tries to access a non existing subdomain (like szdakshd.domain.com) to be redirected to domain.com? Or if not in DNS settings, where?
Related
Join 1M+ other developers and:
Lets start with www,
DNS
you will want to add an A-record with just www in it for your domain.
this will make www go to your droplet.
Apache Config File
after that, you will want to add www as an Alias in your site config file, (if you are using Apache). This should be located in /etc/apache2/sites-enabled
find the section where it says:
and add this under it:
While you are there, make sure that you have a section that has this(replace yourwebfolder with whatever you use for your root web folder)
reload Apache and now you should be able to get to your site using either www.yourdomain.com or just yourdomain.com
that will at least take care of www. You can use the same idea for other other sub-domains.
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
I used an A record and that solved the issue. Thanks!
Can you please share your A rerocrd. Thanks
DNS doesn’t do redirection. You have to configure it in your webserver.
@sierracircle What Apache version is the advice for? What Linux distro is this for? I tried this and got this error on a CentOS 7 running Server version: Apache/2.4.6 (CentOS) and I got this error:
First of all, aren’t we supposed to be editing our Apache Config Files located in /etc/httpd/sites-available? not sites-enabled?
Secondly, is our example.com.conf supposed to look like this advice:
This is my question. And lastly, isn’t yourwebfolder supposed to be called a document root? Or are they different? My last question is for Digital Ocean. Can we please get a qualified document that helps CentOS 7 customers make it so the same page with both www.example.com and example.com have good DNS but we want people who go to both pages only END UP on the example.com domain please? Thanks in advance.
The instructions that @sierracircle posted are correct. So, run the commands above and let’s find out what’s wrong. Make sure you replace /var/www/yourwebfolder with your actual document root path ( /var/www/example.com/public_html ) because you want the block to match files and directories under that path.
One thing I noticed is that you have spaces in some of your paths. I’m not sure if that’s how your config actually is, or if they were simply pasted wrong here.
redirect www to non-www (CNAME needed?)
I would like to avoid duplicated content. Is 301 redirect in nginx sufficent? Is it needed for me to add a CNAME record? My concern is that CNAME record may affect my SEO.
I see that this question has been asked here before, but there was no mention on whether 301 redirect is sufficient without CNAME.
2 Answers 2
A 301 redirect in nginx will suffice. You can also specify your preferred domain in Google Webmaster Tools.
To implement a redirect, your www subdomain must resolve to a web server that issues a redirect to your non-www domain. It doesn’t matter whether you use A records or CNAME records to make that happen.
A DNS CNAME is not a redirect. It just says that the IP address resolves to the same IP address as some other host name. Because of this using a CNAME is neither necessary nor sufficient to implement a redirect. To implement a redirect you need to:
A CNAME records won’t hurt SEO if you do use it. It is very common for websites with good SEO to be configured with either A or CNAME records. Choose whichever your host recommends. The only caveat is that a CNAME record is not allowed to be used for the bare (non-www or @ ) record. If you try to do so your website may not work reliably and any email you have coming to your domain will not be delivered correctly. CNAME records work fine for subdomains though.
Domain IP address for www and non-www for Canonical URL
To handle Canonical URL is it best practice to do a 301 redirect or better to have the same IP Address for both www and non www domain?
Canonical URL/domain wanted is http://example.com
I understand people may have a CNAME record for www (alias, given that CNAME is called Canonical Name); unsure if this is best practice compared to using the same IP address.
3 Answers 3
The mechanisms you describe ( A and CNAME records vs. 301 redirects) are part of two different protocols (DNS and HTTP). A and CNAME records have nothing to do with which site your HTTP server serves for different requests.
Let’s look at two different DNS configurations:
Configuration 1 (CNAME record)
Configuration 2 (A records)
You have to use HTTP 301 redirects to enforce the canonical example.com in HTTP requests. But that has nothing to do with your DNS configuration.
You may try redirect.center. Its redirects domains using DNS only.
So it will fulfill your DNS configurations:
set your DNS record to:
CNAME | www | example.com.opts-https.redirect.center
In DNS the canonical name record is pointing to the «one true DNS entry». The end result is that DNSName1 has the same IP address as DNSName2.
Comprehension is complicated by the fact that the CNAME is not the canonical name. The CName Record points to the canonical name. (The canonical name is the A record).
Canonical link: For search engines the canonical link in the html header of a page specifies the «one true page». You can get to multiple pages but you use the canonical link to tell the search engine that this page is the same as the other page. Doing this makes the search engine happy that you are not gaming the system by pretending to provide more content where it is only duplication. It only indexes it once.
301 (http) redirects: For search engines this says that page x is now replaced by page y and all the search ranking can be transferred to page y. If it is a «cosmetic» domain-name-standardisation it also tells the search engine to only index one page and is again a way to show that you’re not trying to trick the search engine.
How To Redirect www to Non-www with Nginx on CentOS 7
Published on May 4, 2015
Introduction
If you want to perform this type of redirect with Apache as your web server, you should follow this tutorial instead: How to Redirect www to non-www with Apache on CentOS 7.
Prerequisites
This tutorial assumes that you have superuser privileges, i.e. sudo or root, on the server that is running Nginx. If you don’t already have that set up, follow this tutorial: Initial Server Setup on CentOS 7.
It is assumed that you have Nginx installed. If you do not already have this set up, there are several tutorials on the subject under the Nginx 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 Nginx 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.
Configure Nginx Redirect
In order to perform the 301 redirect, you must add a new Nginx server block that points to your original server block.
Open your Nginx server block configuration in an editor. We’ll add another configuration file in the Nginx include directory, /etc/nginx/conf.d called redirect.conf :
Your original server block should already be defined. 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. This configures Nginx to redirect requests to “www.example.com” to “example.com”. Note that there should be another server block that defines your non-www web server.
To put the changes into effect, restart Nginx:
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, add this server block:
Save and exit. This configures Nginx to redirect requests to “example.com” to “www.example.com”. Note that there should be another server block that defines your www web server.
To put the changes into effect, restart Nginx:
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 Nginx permanent redirect is now configured properly, and your users will be able to access your web server via your non-www and www domain.
Software Engineer @ DigitalOcean. Former Señor Technical Writer (I no longer update articles or respond to comments).



