Forum Moderators: phranque

Message Too Old, No Replies

Error 400 and 500 on mod rewrite

I get an error instead of a redirection when i try to use mod_rewrite

         

Grethe

8:36 pm on Nov 25, 2008 (gmt 0)

10+ Year Member



Hi I'm trying to do a rewrite: when people type in the adress
asub.example.com
The server should load example.com/asub

My dns i set to:
*.example.com CNAME example.com
I've read that i should use A-name instead, but I don't know the IP, and i don't know if it changes, thats why i use CNAME, instead.


RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !www.example.com$ [NC]
RewriteCond %{HTTP_HOST} ^(www.)?([a-z0-9-]+).example.com [NC]
RewriteRule (.*) $1 [L]

But this is what i get:
For www.sub.example.com an Error 400
And for sub.example.com an Error 500

To see whats wrong and what happens i tried to put in [R,L] insted of just [L] in the code above.
But then i get:
For www.sub.example.com an Error 400
And for sub.example.com an eternal redirect loop

Can you see what I'm doing wrong?

Thank you

[edited by: Grethe at 8:39 pm (utc) on Nov. 25, 2008]

g1smd

8:46 pm on Nov 25, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Your rewrite writes to itself and the new URL matches your rule again, so it rewrites again, and again and again.

Grethe

8:58 pm on Nov 25, 2008 (gmt 0)

10+ Year Member



Ok, thanks. That's the 500 server error right?
What about the 400 bad request error, i'm still getting that with the www.sub.example.com

Grethe

10:26 pm on Nov 25, 2008 (gmt 0)

10+ Year Member



Hmm.. and it still can't redirect unhidden.
sub.example.com gives me the right page now, if i use it with [R]
but if I don't, I still get a internal server error 500.

jdMorgan

1:15 am on Dec 2, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try something like this, to rewrite <subdomain>.example.com/<resource> to /sub_<subdomain>/<resource>

RewriteEngine on
#
RewriteCond $1 !^sub_
RewriteCond %{HTTP_HOST} !www\.example\.com [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?([a-z0-9\-]+)\.example\.com
RewriteRule (.*) /sub_%2/$1 [L]

Note that the "sub_" prefix on the subdomain subdirectories is used to prevent recursion.

I strongly suggest that you reject subdomains with uppercase characters in them, to avoid the resulting confusion from getting a 404 error that reveals the subdomain-subdirectory name in the path. I removed the [NC] from the second RewriteCond for that reason.

You should redirect to canonicalize the main domain and subdomains before doing the internal rewrite, so as to avoid both that problem and duplicate-content problems arising from FQDN-format hostnames, appended port numbers, case errors, extra or missing "www's", etc.

Jim