Mod_rewrite invisibly: works when the target is a file, not when it is a directory

I have this rewrite rule that turns foo.com/test (or foo.com/test/) into foo.com/test.txt:

RewriteRule ^test/?$ test.txt [NC,L] 

It works great and, importantly, never shows the user that the "real" URL is foo.com/test.txt.

Now I want to do the same where the "real" URL is foo.com/testdir, where testdir is the directory:

 RewriteRule ^test2/?$ testdir [NC,L] 

It rewrites, but shows that it is rewriting to the user. Not what I want.

Can anyone explain what Apache says here and the best solution? Just rewriting in testdir / index.php does not work for me, because the index.php code does not have the right working directory. (It works as if it were foo.com/index.php, as well as css files and are not yet listed in foo.com/testdir/.) Perhaps the correct solution is to change the contents of index.php to reference testdir / foo. css instead of just foo.css, but I'm lazy. Also, I would prefer that the rewrite rule should not know if index.php or index.html or something.

Adding

Thanks to the first answer, now I see the essence of my problem: if I want the user to use the me.com/foo URL and get into the "real" me.com/somedir URL, then I need to choose between two undesirable things:

  • The URL is noticeably rewritten (user can see me.com/somedir).
  • The stuff in somedir works like the root directory. Therefore, I must, for example, change all the paths in somedir / index.php. Like "somedir / style.css" and not just "style.css", as I used to go directly to the "real" URL, me.com/somedir

I think the only answer to this question is to suck it and change these paths. Or just rename the directory "somedir" to "foo", but I cannot do this for other reasons.

+3
source share
1 answer

Add a trailing slash:

 RewriteRule ^test2/?$ testdir/ [NC,L] 

http://foo.com/testdir is not a valid URL in a directory, Apache is looking for a testdir file, and since testdir is actually a directory, Apache is trying to fix this by redirecting testdir /. Thus, while your rewritten work, the subsequent slash error has been fixed by redirecting to testdir /.

You may also need to add the base href tag to the head of your document, otherwise the relative links will break:

 <base href="/"> 
+2
source

All Articles