Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm not even sure if I'm going about this the right way, so I'm going to present the entire problem here.

I have a site with URLs that look like this:

and I'm redirecting like so:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*?)/(.*?)$ $2?key=$1

and this MOSTLY working. My problem is the following two URLs end up not being equivilent:

The 2nd example behaves as expected, redirecting to index.php at the root level, and passing along 'my-key' as the parameter.

The first example fails with a not found error.

Is there a way to add a rule that says if the file isnt found, then fetch index.php?key=$key or am I approaching this from the wrong angle?

share|improve this question
add this RewriteRule ^(.*)$ index.php?key=$1 [L] right after RewriteRule ^(.*?)/(.*?)$ $2?key=$1 and tell me how it goes. – Prix Oct 20 '10 at 1:49
everything rewrites to index, also tried putting a [L] flag after the first rewrite rule -- I read somewhere that [L] isn't honored in .htaccess files, not sure if that's true or not – user57632 Oct 20 '10 at 2:17
as long as the rule is meet it is honored. – Prix Oct 20 '10 at 2:37

Your problem is basically the regex. You are trying to match anything followed by a slash, and followed by anything.

You should try:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)$ $2?key=$1 [R,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^.*/$
RewriteRule ^(.*)$ ?key=$1 [R,L]

The first block is your config, and works just like you need. The second one applies only if there is no trailing slash, which is what you want.

the only drawback is that if anyone asks for an URL which does not have its corresponding page.php after the key (let's say /some-key/nonexistant.php), it will be redirected to ?key=nonexistant.php (don't know how to call this, feature or bug :P).

The default page for the request /?key=your-key is you DefaultIndex

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.