views:

22

answers:

2

I'd like to redirect all top level directories to a file using mod_rewrite.

So the following should redirect there:

- http://example.com/test
- http://example.com/test8/ 
- http://example.com/test_9231/

The following should NOT redirect there:

- http://example.com/test.php
- http://example.com/test_9231/test/
- http://example.com/test/test.php
- http://example.com/test_9231/test

None of the directories will physically exist. Directory names will only contain these characters: A-Za-z0-9_-

I tried this RewriteRule /(.*) /index.php [L] but subdirectories are still redirected.
I thought adding a slash after the 2nd parenthesis would do the job, but it just broke the redirecting.

+1  A: 
RewriteRule ^/[A-Za-z0-9_-]+/?$ /index.php

This will match a slash, then a name according to your spec, then another optional slash, then end of string, so subdirectories won't match

unbeli
I get error 404 when going to http://example.com/test/
Bob the Knob
are you doing this in .htaccess? Do you have other rewrite rules?
unbeli
Yes, in .htaccess. I do have other rules, but I tested your code without them and I get the same result.
Bob the Knob
OK, in .htaccess you need to remove the first "/", making it this:RewriteRule ^[A-Za-z0-9_-]+/?$ /index.php
unbeli
works perfectly now, thanks :D
Bob the Knob
A: 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/?[^/]+/?$ /index.php [L]
Wrikken
Everything is fine, except that http://example.com/test.php redirects too
Bob the Knob
Yeah, didn't bother to catch the '.', as I assumed either a file would exists or you'd want to create a nice 404 page in PHP itself (I would, nobody is helped with generic 404's, a nice page with hints and / or searchform would be preferable IMHO). That was not the question though, so indeed, doesn't fit the bill.
Wrikken