Domanda

I am running several TLD's on my server, and I am trying to redirect them all from non www to www, which works quite well, with a few exceptions I would need to fix.

Issue one is a generic code, which works well, with the exception that the subdomains are being redirected, too, which was not suppose to happen. Here is the code:

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

if I could manage this one not to redirect the sub domains, that would be the perfect solution.

I have also tried this one, which is a bit more code and therefore not really nice, bit it does not redirect the subdomains. But, there is another problem: The url sample.com/folder/folder2/index.html is being redirected to www.sample.com instead of www.sample.com/folder/folder2/index.html

Here is the code:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^sample\.com [NC]
RewriteRule ^(.*) http://www.sample.com/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^sample\.es [NC]
RewriteRule ^(.*) http://www.sample.es/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^sample\.co.uk [NC]
RewriteRule ^(.*) http://www.sample.co.uk/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^sample\.nl [NC]
RewriteRule ^(.*) http://www.sample.nl/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^sample\.fr [NC]
RewriteRule ^(.*) http://www.sample.fr/$1 [L,R=301]

Any idea on how I can fix the first method so it does ignore requests from subdomains, such as sub.sample.com AND redirect all requests to www version, including URLS like sample.com/folder/folder2/index.html to www.sample.com/folder/folder2/index.html?

È stato utile?

Soluzione

Not sure why the second thing is happening at all. Using your code, when I request: sample.com/folder/folder2/index.html, I get redirected to www.sample.com/folder/folder2/index.html. Are you sure there's not another htaccess file somewhere or if index.html is doing something?

As for the first issue, try:

RewriteCond %{HTTP_HOST} ^([a-z0-9_-]+\.([a-z]){2,3}(?:\.[a-z]{2}|))$ [NC]
RewriteRule ^(.*)$ http://www.%1/$1 [L,R=301]

Altri suggerimenti

You can use this rule to avoid adding www to subdomains:

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top