Forum Moderators: phranque
RewriteEngine On
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !^www\.example\.co\.uk$
RewriteRule (.*) https://www.example.co.uk/$1 [R=302,L]
RewriteRule ^(.*)$ www.example.co.uk/$1 [R=301,L]
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !^www\.example\.co\.uk$
RewriteRule (.*) https://www.example.co.uk/$1 [R=301,L]You don't need anchors in the pattern (.*) because this part is greedy by default: start capturing as soon as you can, go on as long as you can. I'm just trying to ensure that *whatever* someone puts in the address bar before the word example.com, it will always resolve to www.example.com
# if the requested protocol is not HTTPS or
RewriteCond %{HTTPS} !on [OR]
# if the provided Host header value (if any) is not exactly the canonical hostname (or null)
RewriteCond %{HTTP_HOST} !^(www\.example\.co\.uk)?$
# externally redirect any such noncanonical protocol or hostname requests using a 301 status code to the same requested path (and possibly query string) on the canonical protocol and hostname
RewriteRule (.*) https://www.example.co.uk/$1 [R=301,L]
it will always resolve to www.example.com
...whatever anyone puts before the actual domain name
Can anyone put whatever before the actual domain name?One advantage of expressing the rule as a !negative is that it doesn't matter. Your host/DNS might enable wild-card subdomains by default--not that you're likely to get a lot of really off-the-wall requests, even so. (Do malign robots run around asking for forums.example.com, blog.example.com and so on?)
to avoid an infinite redirect chain for requests by HTTP/1.0 clients that don't provide a Host request headerThe (parentheses)? part does no harm; my own htaccess files use it. But if you're on shared hosting it is almost certainly not needed, since requests without a Host: header will never make it as far as your site. (Hurrah! One whole category of stupid robots you never have to set eyes on!)