Search code examples
apache.htaccessmod-rewrite

.htaccess domain name always with www


I have this code taken from another post here in my main .htaccess file :

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^.*/sensors/.*$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

which forces site to be opened via secure connection exept the folder named "sensors"

My question is what pieces of code is needed here to force webisite to always open with www at the beginning. How to apply this "www" rule to all folders exept the folder named "sensors" ? Thanks in advance for your help


Solution

  • You could just add another rule, before your existing "HTTP to HTTPS" rule that redirects non-www to www (and HTTPS), excluding "sensors". For example:

    # Redirect non-www to www (and HTTPS), excluding "/sensors/"
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule !(^|/)sensors/ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    
    :
    

    RewriteCond %{REQUEST_URI} !^.*/sensors/.*$
    

    Note that this regex (^.*/sensors/.*$) is the same as simply /sensors/ and matches "/sensors/" anywhere in the URL-path (or rather, does not match "/sensors/" anywhere in URL-path, due to the ! prefix - but this is not part of the regex). But this condition can be moved to the RewriteRule pattern, as in the rule I posted above.