apache - Mod_rewrite 不可见 : works when target is a file, 当它是目录时不是

标签 apache url mod-rewrite url-rewriting friendly-url

我有这个重写规则,将 foo.com/test (或 foo.com/test/)变成 foo.com/test.txt:

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

它工作得很好,重要的是,它永远不会向用户透露“真实”URL 是 foo.com/test.txt。

现在我想做同样的事情,其中​​“真实”URL 是 foo.com/testdir,其中 testdir 是一个目录:

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

它执行重写,但向用户显示重写。这不是我想要的。

谁能解释一下 Apache 的想法以及最佳解决方案吗?仅重写 testdir/index.php 对我来说不起作用,因为 index.php 中的代码没有正确的工作目录。 (它的运行就好像它是 foo.com/index.php 一样,而 css 文件和诸如此类的东西都在 foo.com/testdir/中。)也许正确的解决方案是更改 index.php 的内容以引用 testdir/foo。 css 而不仅仅是 foo.css 但我很懒。另外,我希望重写规则不必知道它是index.php还是index.html还是what-have-you。

附录

感谢第一个答案,我现在看到了问题的本质:如果我希望用户使用 URL me.com/foo 并访问“真实”URL me.com/somedir 那么我必须选择在两个不受欢迎的事情之间:

  1. 网址明显被重写(用户可以看到 me.com/somedir)。
  2. somedir 中的内容就像在根目录中一样运行。因此,例如,我必须更改 somedir/index.php 中的所有路径。就像“somedir/style.css”,而不是像我直接访问“真实”URL me.com/somedir 时使用的“style.css”

我认为解决这个问题的唯一答案就是忍住并改变这些路径。或者只是将目录“somedir”重命名为“foo”,但由于其他原因我无法这样做。

最佳答案

添加尾部斜杠:

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

http://foo.com/testdir不是该目录的有效 url,Apache 会查找名为 testdir 的文件,并且由于 testdir 实际上是一个目录,Apache 会尝试通过重定向到 testdir/来修复它。因此,虽然您的重写有效,但随后的缺失斜杠错误已通过重定向到 testdir/修复。

您可能还需要将基本 href 标签添加到文档的头部,否则相关链接将中断:

<base href="/">

关于apache - Mod_rewrite 不可见 : works when target is a file, 当它是目录时不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1685030/

相关文章:

php - mod_rewrite 到文本/类型/id

apache - 从 symfony 的 url 中删除 www 和 index.php

http - 使用 .htaccess 将 http 重定向到 https 时,某些网址会出现奇怪的 401 错误

apache - 来自脚本路径的 a2ensite

apache - 是什么导致 apache 崩溃并出现错误 "Inconsistency detected by ld.so"?

java - 使用 Java 检索 URL 中的参数

php - 如何使用自定义变量更改 url 变量

php - LAMP 中的 XAMPP 和 WAMP,哪个最好?

php - 加载 index.php 作为我在 PHP 中的第一页

api - 搜索 API - HTTP 查询参数格式