开发者

Dynamic URL rewriting with PHP in root and non-root directories

For my program I use dynamic URL rewriting with PHP:

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

In PHP I then break down the URL in its different parts. For example http://myhost/foo/bar returns foo bar. The problem I have is if the program is not located in the root directory of the server, for example http://myhost/this/is/a/folder/hereistheprogram/foo/bar, because then the script returnes this is a folder hereistheprogram foo bar. Now have the problem that I can't differentiate between the folders and the URL parameters.


You need to know what the path to the script file is. You can do that by either explicitly declaring the path prefix or by determining it automatically, for example:

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

Then you can use that prefix and strip it from the request URI path:

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

By the way: It would be better if you don’t pass the request URI path explicitly to your index.php but retrieve it from $_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);

And the corresponding mod_rewrite rule:

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


Not too sure of the exact problem but..

Could you have constant 'foo' identifier used in the urls to identify where to break the string?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜