.htaccess - how to force "www." in a generic way?

.htaccess, mod-rewrite

Solution

I would use this rule:

RewriteEngine On
RewriteCond %{HTTP_HOST} !=""
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

The first condition checks whether the Host value is not empty (in case of HTTP/1.0); the second checks whether the the Host value does not begin with `www.`; the third checks for HTTPS (`%{HTTPS}` is either `on` or `off`, so `%{HTTPS}s` is either `ons` or `offs` and in case of `ons` the `s` is matched). The substitution part of `RewriteRule` then just merges the information parts to a full URL.

Problem

This will change `domain.example` to `www.domain.example`: ``` # Force the "www." RewriteCond %{HTTP_HOST} !^www\.domain\.example$ [NC] RewriteRule ^(.*)$ `http://www.domain.example/$1` [R=301,L] ``` How do I replace the "domain" part so that this works on any domain?

Original source