如何在IIS中使用REQUEST_URI而不是REDIRECT_URL来获得相同的功能


How to use REQUEST_URI instead of REDIRECT_URL with IIS to get same functionality?

我有一个使用$_SERVER['REQUEST_URI']的PHP应用程序。如果我使用Apache web服务器,我的应用程序运行良好。如果我使用Microsoft IIS web服务器,则应用程序不工作,因为$_server['REQUEST_URI']为null。我发现$_SERVER['REDIRECT_URL']可用于Microsoft IIS。

我的问题是如何使用$_SERVER['REDIRECT_URL']而不是$SERVER['REQUEST_URI']使用Microsoft IIS web服务器获得相同的功能?

我不能简单地用REDIRECT_URL替换REQUEST_URI,因为它不包含查询字符串,我的PHP应用程序需要它。

我的php代码:

function filterAppUrl($url)
{  
  $url = htmlspecialchars($url);
  $url = str_replace('"', '',  $url);
  $url = str_replace("'", '',  $url);
  return $url;
}
function setAppURL()
{
   $url = $this->filterAppUrl($_SERVER['REDIRECT_URL']);
   $url = substr($url, 1, strlen($url));
   $this->full_url = $url;
   $this->url = explode('/', $url);
}

我的.htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

IIS 的我的Web.config

<?xml version="1.0"?>
<configuration>
 <system.webServer>
 <defaultDocument>
  <files>
    <remove value="index.php" />
    <add value="index.php" />
  </files>
 </defaultDocument>
<rewrite>
 <rules>
     <rule name="Main Rule" stopProcessing="true">
         <match url=".*" />
         <conditions logicalGrouping="MatchAll">
             <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
             <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
         </conditions>
         <action type="Rewrite" url="index.php" />
     </rule>
 </rules>
</rewrite>
</system.webServer>
</configuration>

类似于:

function setAppURL()
{
   if (isset($_SERVER['REDIRECT_URL'])) {
      $url = $this->filterAppUrl($_SERVER['REDIRECT_URL']);
   } else {
      $url = $this->filterAppUrl($_SERVER['REQUEST_URI']);
   }
   $url = substr($url, 1, strlen($url));
   $this->full_url = $url;
   $this->url = explode('/', $url);
}

这基本上就像是说:如果REDIRECT_URL被设置而不是null,那么就使用它。否则就使用REQUEST_URI

我遇到了同样的问题,尽管$_SERVER数组的确切内容在各种IIS配置之间似乎有所不同,但这在Azure计算机上适用。

我使用这段代码在Unix和IIS上获得对请求的URL的有效引用,而不需要查询字符串:

        // on unix we just get what we need
        if(isset($_SERVER['REDIRECT_URI'])) {
            $base_uri = $_SERVER['REDIRECT_URI'];
        }
        // IIS doesn't have a nice way to get the request url without the query string,
        // so grab the request uri until the start of the query string
        else {
            $base_uri = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
        }

对于类似的urlhttp://www.example.com/path/to/page?article=123,$base_uri在Unix和IIS上都将是/path/to/page