non-www to www for any domain (primary and parked domains)

mod_rewrite .htaccess canonical non-www to www parked domains

&nbsp

dareRock

12:40 pm on Jun 6, 2009 (gmt 0)

Hey there,

Hoping someone out there has done this before. I 'think' I'm on the right track, but haven't gotten the results I'm hoping for.

I have a hosting account (LAMP) that will always have one primary domain, but could also have several parked domains. Using .htaccess and mod_rewrite, for *any* domain, I want to add the 'www.' when it is not present.

The lower part of the process then re-directs everything to index.php in a subdir.

I think the problem lies in the RewriteRule - I don't think my syntax is correct. Also, I wonder if the domain matching pattern is a little overkill and I should just look for a 'www.' before any TLD?

jdMorgan

1:12 pm on Jun 6, 2009 (gmt 0)

Yes, you can simplify the pattern in one way, but you'll need to account for FQDN-foramt hostnames and also for the possibility that the hostname may have an appended port number, e.g. "example.com.:80" is a perfectly-valid requested hostname.

However, you also need to check that the "www" is missing before invoking the redirect, otherwise you'll get a loop. And you must back-reference the captured "www-less" domain in the substitution URL:

Important: Replace the broken pipe "¦" character with a solid pipe character before use; Posting on this forum modifies the pipe character.

Thanks Jim!

g1smd

4:13 pm on Jun 6, 2009 (gmt 0)

Watch out! If you have not got a robots.txt file in place on the site, a request for robots.txt is rewritten to your script.

Going extensionless and using a better pattern than "." would ensure that only extensionless URL requests would be rewritten.

At the same time you could lose the resource hungry -f check from your rule. You would probably still need the -d rule though.

It wouldn't need to make a file-system check when images, CSS, JS, SE account verification files (WMC/Analytics/etc), and so on, are requested.

jdMorgan

5:43 pm on Jun 6, 2009 (gmt 0)

Further, the domain canonicalization rules should *not* have "/subdir" in them, because they should be located in .htaccess in your site root. Otherwise, they'll only apply to "wrong" domains on requests to that subdir. (This may not apply if the "/subdir" in question was created by your 'control panel' to support add-on domains, and those add-on domains treat "/subdir" as their root directory.)