I am trying to remove the www. at the beginning of our domain name via .htaccess. I'm doing it like this:

RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [R,NC]

It seems to word wonderfully.

I would like to retain the www. when someone accesses the site securely with https. I found a bit of code on the web that described how to force the www. except on a certain folder ("blog" in this case):

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule !^blog(/.*)?$ http://www.domain.com%{REQUEST_URI} [R,L]

I thought if I changed it a little, I could make at least a single folder keep the www. like this:

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
RewriteRule !^secure(/.*)?$ http://.domain.com%{REQUEST_URI} [R,L]

It didn't work. I got a redirect loop error.

Any ideas?

Been a while since I looked at this.
I believe this works:

# Check if there is no www in the HTTP_HOST, then check if HTTPS is on.
# If both are true, ensure that www is on the URL.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS} on
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

# Check if www is in the HTTP_HOST, then check if HTTPS is NOT on.
# If both are true, ensure that www is removed from the URL.
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

This is a domain neutral approach that can be used on most any site without needing to update on a site by site basis.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.