I'm working on a site that only works if you type in www. Only the www subdomain has an A record. The bare/naked domain is unable to be given an A record. The naked domain can also not be given a DNS Alias. This means the site without "www" shows an error in your browser.
I'm trying to think through any creative solution that may solve this usability issue.
Would an htaccess rewrite rule such as:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
work in this scenario to force users to the www working site and to keep users from seeing an error in their browser?
I'm thinking it likely does NOT work because the htaccess file would only be accessed when users already typed in www (which has the A record). Is that thinking correct?
(Additional examples of htaccess code are in this thread) Redirect non-www to www in .htaccess
If this isn't a valid option, any other creative solutions that might work?
CodePudding user response:
No, .htaccess
rules won't work if the DNS isn't pointing to them. The only way to issue a redirect is by pointing the DNS to a web server that redirects.
CNAME
records never work for the domain apex, so they are never an option. The only DNS records that will resolve a website for the domain apex are A
records. I suspect that you are using a web host that doesn't give you an IP address to put into the A record, only a name. They probably warn that the IP address could change without warning. There are other possible solutions in this type of situation:
Let your web host be your DNS host
Many web hosts will offer to host your DNS for you. They can then keep your A
and CNAME
records up to date for you. They would be able to use A records at the APEX and change them as needed. If your web host offers this service, you would change your NS
records at your DNS registrar to point to values given to you by your web host. Usually something like ns1.example.com
and ns2.example.com
.
Use ANAME
or ALIAS
records
Many DNS hosts now allow your to enter a name but serve it as an A
record. The DNS host periodically (like every few minutes) looks up the IP address for the name and serves an A
record with the current value. These records have different names at different DNS hosts, but they are usually called ANAME
or ALIAS
records. If your current DNS host doesn't offer this service, you could switch to a more capable DNS host that does so.
Use a third party redirect service
If your existing web host won't give you an IP address to use in an A
record, you can use an alternate web host that will do so for the redirects. Most web hosting will give you an IP address to put into DNS records that won't change without notice. It is possible to find an alternate host for your domain apex and use that hosting only to do the redirect to www. Your www CNAME
record would continue to point to your existing host.