如何让所有 URL 都通过单个 PHP 文件运行?

如何让所有 URL 都通过单个 PHP 文件运行?

这些形式的 URL 中的 MVC 系统如何强制所有请求通过单个 index.php 文件?

http://www.example.com/foo/bar/baz
http://www.example.com/goo/car/caz/SEO-friendly-name-of-the-object
http://www.example.com/hey/you

编辑:当我尝试下面的重写规则时出现此错误:

[error] [client 127.0.0.1] Invalid URI in request GET / HTTP/1.1
[error] [client 127.0.0.1] Invalid URI in request GET /abc HTTP/1.1

编辑:哦,这是 /index.php 的完整内容。当我删除重写规则时,它会输出“/”或“/index.php”,或者我得到 404 错误。

<?php
echo htmlspecialchars($_SERVER['REQUEST_URI']);
?>

已解决:我在重写规则中的 index.php 前面添加了一个 /,然后它就起作用了:

再次解决:原来只需要 / 因为我运行的是 2.2.4。当我升级到 2.2.11 时,就不再需要 / 了。

答案1

如果您使用 Apache,请通过以下方式使用重写mod_rewrite

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]

这会透明地将您的 URL 重写为 »index.php?q=foo/bar/baz«。

第 2 行和第 3 行告诉重写引擎,如果 URL 指向现有文件或目录,则不要重写 URL。这对于访问 httpd 服务器提供的真实文件是必要的。

答案2

以下代码使用 Apache 的 mod_rewrite 重写所有未指向要映射到 index.php 的物理文件或目录的 URL。最终结果将是:

http://www.example.com/index.php/foo/bar/baz
http://www.example.com/index.php/goo/car/caz/SEO-friendly-name-of-the-object
http://www.example.com/index.php/hey/you

重写规则:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [PT,L,QSA]

解释:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

以上两行都表明该规则不适用于常规文件(-f)或目录(-d)。

RewriteRule ^(.*)$ index.php/$1 [PT,L,QSA]

有关如何创建 mod_rewrite 规则的更多信息可从 Apache 网站收集: http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html

相关内容