使用PHP在根目录和非根目录中进行动态URL重写

时间:2011-03-19 11:47:49

标签: php apache .htaccess url-rewriting url-routing

对于我的程序,我使用PHP进行动态URL重写:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    #Rewrite the URI if there is no file or folder
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    #rewrite all to index.php
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

在PHP中,我在其不同部分分解了URL。例如,http://myhost/foo/bar会返回foo bar。我遇到的问题是程序是否位于服务器的根目录中,例如http://myhost/this/is/a/folder/hereistheprogram/foo/bar,因为脚本返回this is a folder hereistheprogram foo bar。现在有一个问题,我无法区分文件夹和URL参数。

2 个答案:

答案 0 :(得分:2)

您需要知道脚本文件的路径是什么。您可以通过显式声明路径前缀或自动确定它来执行此操作,例如:

$basePath = dirname($_SERVER['SCRIPT_NAME']);

然后您可以使用该前缀并从请求URI路径中删除它:

if (substr($requestPath, 0, strlen($basePath)+1) === $basePath.'/') {
    $path = substr($requestPath, strlen($basePath));
} else {
    $path = $requestPath;
}

顺便说一下:如果你没有将请求URI路径明确地传递给 index.php 但是从$_SERVER['REQUEST_URI']检索它会更好:

$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$_SERVER['REQUEST_URI_QUERY'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);

相应的mod_rewrite规则:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]

答案 1 :(得分:1)

不太确定确切的问题,但是..

你可以在网址中使用常量'foo'标识符来识别字符串的中断位置吗?

相关问题