Redirect domain to https & www but subdomain non-www

For a website that uses subdomains it would be better to redirect domain to https & www but subdomain non-www. Clearly, there are hundreds or more posts on the web about domain and subdomain redirection in https, www, non-www. But why sometimes even the most perfect code does not work?
The ways to redirect domain to https & www are many and easy. While to redirect subdomain to non-www a little more work is needed.
First of all you have to install an SSL. It’s your choice if you want to buy one or generate a free one from Let’s Encrypt. At Blogger you can get it for free without having to go to third party providers.
There are clear and precise rules about domain and subdomain redirection. As for https, www and non-www there is an easy solution if we follow the rules before and after placing the redirect in .htaccess or cPanel.
Let’s say we want to have a domain like this:
https://www.example.com
… and a subdomain like this:
https://sub.example.com
WWW is technically a subdomain. Maybe it would be better to plan the domain and subdomain structure as in the example above.
Ok let’s clarify the redirection. Here we have introduced two codes, two redirection rules.
But one thing is very important: Before redirect testing do not forget to remove the problems caused by CACHE.
How to redirect primary domain to HTTPS and WWW using .htaccess file?
First, make sure you added “www” CNAME correctly in domain dns manager.
Enter the code below in the .htaccess file in the primary domain directory.
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
RewriteRule (.*) https://www.example.com/$1 [R=301,L]
</IfModule>
Primary domain redirection is easier to implement than subdomain. You can also do this through the Domain DNS Manager or in cPanel.
How to redirect subdomain to HTTPS non-WWW using .htaccess?
Same as in the primary domain, make sure you added “www” CNAME for subdomain correctly in domain dns manager. You can add a CNAME like this: “sub” then “www.sub”.
In the past it did not seem logical to add www.sub for subdomain. But I changed my mind after the tests.
Enter this code in the .htaccess file in the subdomain directory.
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-SSL} !on
RewriteCond %{HTTP_HOST} ^sub\.example\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.sub\.example\.com$
RewriteRule ^/?$ "https\:\/\/sub\.example\.com\/" [R=301,L]
Make these codes work.
First, if you are using WordPress refresh permalinks.
- Go to settings then click on Permalinks
- Change the structure
- Click Save
- Restore your structure as before and click save again
Clear the CACHE everywhere, not only in your browser but also in cache plugin if you have any, on the server in CDN etc. The path from WordPress to the visitor browser must be clean.