Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This will change domain.com to www.domain.com:

# Force the "www." RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC] RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L] 

How do I replace the "domain" part so that this works on any domain?

like image 484
StackOverflowNewbie Avatar asked Feb 06 '11 21:02

StackOverflowNewbie


People also ask

How do I redirect www to non-www in htaccess?

E.g.: RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^www.example.com/$ [NC] RewriteRule ^(. *)$ http://www.example.com [R=301,L] ... @BobbyS I used the solution in this article. It redirects www and HTTP to non-www HTTPS and also handles the trailing / .


Video Answer


2 Answers

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.

like image 195
Gumbo Avatar answered Oct 10 '22 00:10

Gumbo


This will do it:

RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] 
like image 38
Martin Drapeau Avatar answered Oct 10 '22 00:10

Martin Drapeau