mod_rewrite & PHP; $_SERVER['REQUEST_URI']

2019-05-21 18:12发布

问题:

Quick one:

I'm curious if anyone knows of certain circumstances under which $_SERVER['REQUEST_URI'] would contain a different value than $_GET['_uri'], given the following .htaccess for the latter:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ?_uri=$1 [L,QSA]

I've been using the latter method $_GET['_uri'], and while I'm aware that mod_rewrite would still be necessary, I'd like to get away from storing the URI as a query parameter.


Well, I've found one I didn't notice before; when the application bootstrap to which mod_rewrite forwards is not in the root web directory, $_SERVER['REQUEST_URI'] contains the parent directories, whereas $_GET['_uri'] only contains the latter URI component. Example:

Bootstrap is /subdir/index.php
Requesting http://localhost/subdir/foo/bar/baz/

$_SERVER['REQUEST_URI']  "/subdir/foo/bar/baz/"
$_GET['_uri']            "foo/bar/baz/"

In order to replicate the result of $_GET['_uri'], decided to use this:

$prefix = trim(dirname(strtr($_SERVER['PHP_SELF'], '\\', '/')), '/') . '/';
$uri = trim($_SERVER['REQUEST_URI'], '/') . '/';
if(substr($uri, 0, strlen($prefix)) == $prefix){
    $uri = substr($uri, strlen($prefix));
}

But I've not used $_SERVER['PHP_SELF'] often in the past, and now have read that it carries certain vulnerabilities and/or inconsistencies with it's use.

回答1:

http://example.com/meow?param=value&_uri=hihihi
  • Expected $_GET['_uri'] result: meow
  • Actual result: hihihi
  • $_SERVER['REQUEST_URI'] value: /meow?param=value&_uri=hihihi
  • $_SERVER['REDIRECT_URL'] value: /meow

All because of [QSA] flag.

Use $_SERVER['REQUEST_URI'] and/or $_SERVER['REDIRECT_URL'] instead.

The above is for Apache. On IIS 7.x it may be a bit different.