开发者

Mod_rewrite invisibly: works when target is a file, not when it's 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 perfectly and, importantl开发者_如何学运维y, never reveals to the user that the "real" URL is foo.com/test.txt.

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

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

It does the rewrite but it shows that rewrite to the user. Not what I want.

Can anyone explain what Apache is thinking here, and the best solution? Just rewriting to testdir/index.php doesn't work for me since then the code in index.php doesn't have the right working directory. (It runs as if it were foo.com/index.php and the css files and whatnot are in foo.com/testdir/.) Perhaps the right solution is to change the contents of index.php to refer to testdir/foo.css instead of just foo.css but I'm lazy. Also, I'd rather the rewrite rule didn't have to know whether it's index.php or index.html or what-have-you.

Addendum

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

  1. The URL gets visibly rewritten (the user can see me.com/somedir).
  2. The stuff in somedir runs as if it's in the root directory. So I have to change all the paths in somedir/index.php, for example. Like "somedir/style.css" instead of just "style.css" like I used when going straight to the "real" URL, me.com/somedir

I'm thinking the only answer to this is to suck it up and change those paths. Or just rename the directory "somedir" to "foo" but I can't do that for other reasons.


Add the trailing slash:

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

http://foo.com/testdir isn't a valid url to the directory, Apache looks for a file called testdir, and because testdir is actually a directory Apache tries to fix it by redirecting to testdir/ . So while your rewrite worked the subsequent missing slash error was fixed by redirecting to testdir/.

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

<base href="/">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜