Tag Archives: domains

Exclude redirecting subdomains in htaccess RewriteRule

Redirecting websites to be secure with https can be a little tricky.  I had to exclude redirecting subdomains in htaccess RewriteRule.  This mostly because a number of my subdomain’s code lives within a subfolder of my primary domain.

How to Exclude redirecting subdomains in htaccess RewriteRule

To exclude redirecting subdomains in htaccess RewriteRule use the following RewriteCond. This tell Apache to only use the redirect if the request is to the top level domain, not a subdomain.

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$

For instance, my .htaccess for jstassen.com looks like:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ https://jstassen.com/$1 [R=301,L]

This regex only fully matches the base domain. You can see this on Debuggex.

Exclude redirecting subdomains in htaccess RewriteRule

Note: websites with www are considered a subdomain. For instance www.jstassen.com is a subdomain of jstassen.com just like blog.jstasseen.com. This rule will therefore exclude the www subdomain. I have my www subdomain auto redirect to remove the www which I recommend.