Forum Moderators: phranque

Message Too Old, No Replies

htaccess, mod_rewrite, and subdirectory

How to force www in domain when in subdirectory

         

hooter

1:53 pm on Oct 1, 2005 (gmt 0)

10+ Year Member



Hi,

In my root public document directory here is what I have in my htaccess file to force "www" into the canonical domain:

# FORCE WWW IN URL
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
# END FORCE WWW IN URL

This works fine for the root domain url but I noticed for a subdirectory this is what happens:
I try to go to http://example.com/subdirectory without trailing slash I get a rewritten URL that is like this:
http://www.example.com//server/file/system/path/subdirectory

If I type in http://example.com/subdirectory/ (note trailing slash this time) I just get redirected to http://www.example.com

What is the recommended method to assure that the www is used throughout your directory structure and if I need a supplementary htaccess file in each subdirectory what examples should I be following.

Many thanks.

[edited by: jdMorgan at 1:08 am (utc) on Oct. 2, 2005]
[edit reason] Example.com [/edit]

billegal

2:51 pm on Oct 1, 2005 (gmt 0)

10+ Year Member



Try this:

# FORCE WWW IN URL
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(/.*)$ http://www.example.com/$1 [R=301,L]
# END FORCE WWW IN URL

[edited by: jdMorgan at 1:10 am (utc) on Oct. 2, 2005]
[edit reason] Example.com [/edit]

hooter

4:35 pm on Oct 1, 2005 (gmt 0)

10+ Year Member



billegal,

That almost works - per your example here is what I have in my root public document directory now:

# FORCE WWW IN URL
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(/.*)$ http://www.example.com/$1 [R=301,L]
# END FORCE WWW IN URL

If I go to example.com it takes me to www.example.com/ (good)

If I go to example.com/ it takes me to www.example.com/ (good)

If I go to example.com/subdirectory it takes me to www.example.com/subdirectory/ (good)

If I go to example.com/subdirectory/ I get a 500 Internal Server error (not good) :)

Many thanks for your response.

[edited by: jdMorgan at 1:12 am (utc) on Oct. 2, 2005]
[edit reason] Example.com [/edit]

hooter

12:49 am on Oct 2, 2005 (gmt 0)

10+ Year Member



Never mind all - operator error...

For any newbies (like me) following this thread the original code posted works fine and handles subdirectories as well.

Putting the original in your root htaccess handles all instances including subdirectories:
# FORCE WWW IN URL
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
# END FORCE WWW IN URL

We now return to our regularly scheduled programming and my apologies for the wasted bandwidth. ;)

[edited by: jdMorgan at 1:12 am (utc) on Oct. 2, 2005]
[edit reason] Example.com [/edit]