2

我有一个非常奇怪的问题

我正在玩弄 .htaccess 并尝试将所有请求重定向到 /test/ 文件夹的索引文件。

我的站点位于本地 htdocs 文件夹中的文件夹 /test/ 中。当前不存在其他文件。

我的期望: 当我访问任何 url 时,(例如/test/category/one/)我应该被重定向到/test/index.php

会发生什么 我得到一个404 Not Found

我的 .htaccess 看起来像这样:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /test/index.php?__route=$1 [L,QSA]

我试过设置RewriteBase /test/

这很简单,为什么它不起作用?

我在另一个文件夹中有一个 Wordpress 站点,并且可以完美地使用自定义重写。

我什至将 Wordpress 的 .htaccess 内容复制到了测试站点,用 /test/ 替换了重写基础和最后一条规则。

Wordpress 的 .htaccess :(可在同一服务器上单独安装 WP)

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /test/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /test/index.php [L]
</IfModule>

# END WordPress

我已经为此苦苦挣扎了一段时间,并且在没有帮助的情况下阅读了很多 SO 文章。

我什至写了一个重写日志文件,现在当我浏览到测试站点时什么都没有显示,但是访问 Wordpress 站点会写很多行。

我在 Win64 机器上运行 XAMPP。

任何帮助将不胜感激!=)

4

2 回答 2

5

更新:另外,请确保您的 .htaccess 文件中的行尾设置正确。Apache 有时会因不包含换行符 (\n) 字符的任何内容而窒息。

所以在我看来,你想(在某种程度上)模仿 WordPress 正在做的事情。以下是我在开发一些做同样事情的软件时处理这种情况的方法:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /test
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [L]
RewriteRule ^.*$ /index.php [L]
</IfModule>

对于存在的文件(即通过-f-d测试通过),我们将它们原封不动地提供。否则,我们将传入的请求重定向到 index.php。请注意,/test路径的一部分不包含在 RewriteRule 中,因为 RewriteBase 设置在我们开始的位置。所以,在你的例子中,我认为它最终会是:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /test
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [L]
RewriteRule ^(.*)$ /index.php?__route=$1 [L,QSA]
</IfModule>

FWIW,我不是 .htaccess 专家。过去我只是发现这对我有用。

此外,如果您在共享主机(如 DreamHost)上,您可能需要设置适当的规则以允许默认错误文档。一些共享的网络主机为错误情况提供一个文件(failed_auth.html 就是一个例子)。如果您没有过滤掉这种情况,您最终可能会得到 404。

于 2012-08-16T18:50:03.730 回答
2

这应该可以解决问题:

# Activate the rewrite module.
RewriteEngine On
# Ensure the requested URL is not a file.
RewriteCond %{REQUEST_FILENAME} !-f
# Ensure the requested URL is not a directory.
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?__route=$1 [L,QSA]
于 2012-08-16T19:13:26.533 回答