【发布时间】:2016-08-27 00:35:24
【问题描述】:
我有一个在 WampServer 上本地运行的项目。这是一个类似 MVC 的结构;它将 URL 重写为index.php?url=$1。满员.htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
当我想使用 PHP location: <location> 将用户发送到另一个页面时,由于重写,它不能正确执行此操作(尽管从技术上讲,我总是在 index.php)。
例如,如果我在 http://localhost/project_name/controller/method/ 并且此控制器的构造函数或方法尝试将我发送到:
-
header('location: another_controller/method');发送给我http://localhost/project_name/controller/method/another_controller/method/ -
header('location: /another_controller/method');发送给我http://localhost/another_controller/method/
但我希望它像这样发送给我:
-
header('location: /another_controller/method');发送给我http://localhost/project_name/another_controller/method/
现在我找到的唯一解决方案是:
define('BASE_URL','http://localhost/project_name');
header('location: '.BASE_URL.'/another_controller/method/');
但这也不是完美的,因为每当域或文件夹名称发生更改时,我都必须更改此定义的常量BASE_URL。我也可以在我的 BaseController 中创建一个创建绝对 URL 的方法,但这个方法基本上也只是在 BASE_URL 前面添加。
注意: HTML 的src 和href 属性不会出现同样的问题,它们可以使用相对路径(路径中没有project_name 文件夹)。但是我不明白为什么。因为如果标题 location 导致浏览器将相对 URL 附加到当前位置,为什么它在查找 .css 或 .js 文件时没有相同的行为。
所以...这向我提出了几个问题:
- 如果我有虚拟主机,我会遇到这个问题吗?
- 解决此问题的最佳方法是什么?
- 最好只有完整的绝对 URL?
- 为什么 HTML 的
src和href属性不具有这种行为?
【问题讨论】:
-
你能从开始添加一些你的htaccess文件的代码吗??
-
@HarshSanghani 已添加。
-
能否在 RewriteEngine on 后添加 RewriteBase /project_name/
-
@HarshSanghani 这没有解决。
header('location: /');仍然是http://localhost/而不是http://localhost/project_name/。 -
我注意到你说“
header('location: another_controller/method');将我发送到http://localhost/project_name/controller/method/another_controller/method/”我想指出这将永远是这种情况 - 你忘记了前导斜线。如果没有前导斜杠,它将始终是从当前 URL 开始的相对重定向。不确定这是错字还是完全不相关,但我想我会指出来。
标签: php .htaccess mod-rewrite relative-path absolute-path