Redirect non-www to www *WITH* another rewrite already taking place

99 views Asked by At

This is a relatively standard question, but I cannot seem to get it to work on URLs that already have a rewrite going on.

For example, I have this URL:

http://example.com/this-is-rewritten/
https://example.com/this-is-rewritten/

should go to:

http://www.example.com/this-is-rewritten/
https://www.example.com/this-is-rewritten/

and I want to make sure that it is always WWW in front, if it is not a subdomain URL. So, if we had:

http://subdomain.example.com/this-is-rewritten/

That should NOT go to WWW. This is what I have so far, but it will send you to the under lying URL with querystring, not to the same "/this-is-rewritten/" url. Also, the http or https should be preserved.

RewriteCond %{HTTPS} (on)?
RewriteCond %{HTTP:Host} ^(?:www.)(.+)$ [NC]
RewriteCond %{REQUEST_URI} (.+)
RewriteRule .? http(?%1s)://%2%3 [R=301,L]
2

There are 2 answers

2
Jon Lin On

Try:

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^([^.]+)\.([a-z]+)$
RewriteRule ^(.*)$ http://www.%1.%2/$1 [L,R=301]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^([^.]+)\.([a-z]+)$
RewriteRule ^(.*)$ https://www.%1.%2/$1 [L,R=301]

or if you only have a specific host:

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteCond %{HTTPS}s (?:on(s)|off(s))
RewriteRule ^(.*)$ http%1://www.example.com/$1 [L,R=301]  
2
Andrew On

There's also a common solution from Helicon's FAQ. Works 99.9%

RewriteEngine on

RewriteCond %{HTTPS} (on)?
RewriteCond %{HTTP:Host} ^(?!www\.)(.+)$ [NC]
RewriteCond %{REQUEST_URI} (.+)
RewriteRule .? http(?%1s)://www.%2%3 [R=301,L]