如何在 Windows/IIS 服务器上获取当前页面的完整 URL


How can I get the current page's full URL on a Windows/IIS server?

我将WordPress安装移动到Windows/IIS服务器上的新文件夹中。我正在 PHP 中设置 301 重定向,但它似乎不起作用。我的帖子网址具有以下格式:

http:://www.example.com/OLD_FOLDER/index.php/post-title/

我不知道如何抓取URL的/post-title/部分。

$_SERVER["REQUEST_URI"] - 每个人似乎都推荐 - 返回一个空字符串。 $_SERVER["PHP_SELF"]只是返回index.php.为什么会这样,我该如何解决?

也许,因为你在 IIS 下,

$_SERVER['PATH_INFO']

是您想要的,基于您用来解释的 URL。

对于 Apache,您将使用 $_SERVER['REQUEST_URI'] .

$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
    $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} 
else 
{
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;

对于 Apache:

'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']

你也可以使用HTTP_HOST而不是赫尔曼评论的SERVER_NAME。有关完整讨论,请参阅此相关问题。简而言之,您可能可以使用其中任何一个。这是"主机"版本:

'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']

对于偏执狂/为什么重要

通常,我在VirtualHost中设置ServerName,因为我希望这是网站的规范形式。$_SERVER['HTTP_HOST']是根据请求标头设置的。如果服务器响应该 IP 地址的任何/所有域名,用户可能会欺骗标头,或者更糟糕的是,有人可能会将 DNS 记录指向您的 IP 地址,然后您的服务器/网站将提供具有动态链接的网站建立在不正确的 URL 上。如果使用后一种方法,则还应配置vhost或设置.htaccess规则以强制执行要提供的域,如下所示:

RewriteEngine On
RewriteCond %{HTTP_HOST} !(^stackoverflow.com*)$
RewriteRule (.*) https://stackoverflow.com/$1 [R=301,L]
#sometimes u may need to omit this slash ^ depending on your server

希望有帮助。这个答案的真正意义只是为那些在寻找一种使用 apache :)获取完整 URL 的方法时最终来到这里的人为提供第一行代码

$_SERVER['REQUEST_URI']不适用于

IIS,但我确实发现了这个:http://neosmart.net/blog/2006/100-apache-compliant-request_uri-for-iis-and-windows/这听起来很有希望。

使用此类来获取 URL 工作。

class VirtualDirectory
{
    var $protocol;
    var $site;
    var $thisfile;
    var $real_directories;
    var $num_of_real_directories;
    var $virtual_directories = array();
    var $num_of_virtual_directories = array();
    var $baseURL;
    var $thisURL;
    function VirtualDirectory()
    {
        $this->protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
        $this->site = $this->protocol . '://' . $_SERVER['HTTP_HOST'];
        $this->thisfile = basename($_SERVER['SCRIPT_FILENAME']);
        $this->real_directories = $this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['PHP_SELF'])));
        $this->num_of_real_directories = count($this->real_directories);
        $this->virtual_directories = array_diff($this->cleanUp(explode("/", str_replace($this->thisfile, "", $_SERVER['REQUEST_URI']))),$this->real_directories);
        $this->num_of_virtual_directories = count($this->virtual_directories);
        $this->baseURL = $this->site . "/" . implode("/", $this->real_directories) . "/";
        $this->thisURL = $this->baseURL . implode("/", $this->virtual_directories) . "/";
    }
    function cleanUp($array)
    {
        $cleaned_array = array();
        foreach($array as $key => $value)
        {
            $qpos = strpos($value, "?");
            if($qpos !== false)
            {
                break;
            }
            if($key != "" && $value != "")
            {
                $cleaned_array[] = $value;
            }
        }
        return $cleaned_array;
    }
}
$virdir = new VirtualDirectory();
echo $virdir->thisURL;

添加:

function my_url(){
    $url = (!empty($_SERVER['HTTPS'])) ?
               "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] :
               "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    echo $url;
}

然后只需调用 my_url 函数。

我使用以下函数来获取当前的完整URL。这应该适用于IIS和Apache。

function get_current_url() {
  $protocol = 'http';
  if ($_SERVER['SERVER_PORT'] == 443 || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) {
    $protocol .= 's';
    $protocol_port = $_SERVER['SERVER_PORT'];
  } else {
    $protocol_port = 80;
  }
  $host = $_SERVER['HTTP_HOST'];
  $port = $_SERVER['SERVER_PORT'];
  $request = $_SERVER['PHP_SELF'];
  $query = isset($_SERVER['argv']) ? substr($_SERVER['argv'][0], strpos($_SERVER['argv'][0], ';') + 1) : '';
  $toret = $protocol . '://' . $host . ($port == $protocol_port ? '' : ':' . $port) . $request . (empty($query) ? '' : '?' . $query);
  return $toret;
}

REQUEST_URI是由Apache设置的,所以你不会用IIS得到它。 尝试对 $_SERVER 进行var_dump或print_r,看看那里存在哪些可以使用的值。

URL

的后标题部分位于index.php文件之后,这是在不使用mod_rewrite的情况下提供友好 URL 的常用方法。因此,posttitle 实际上是查询字符串的一部分,因此您应该能够使用 $_SERVER['QUERY_STRING'] 获取它。

使用您正在使用 $_SERVER['REQUEST_URI'] 的 PHP 页面顶部的以下行。这将解决您的问题。

$_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'] . '?' . $_SERVER['argv'][0];

哦,片段的乐趣!

if (!function_exists('base_url')) {
    function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){
        if (isset($_SERVER['HTTP_HOST'])) {
            $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
            $hostname = $_SERVER['HTTP_HOST'];
            $dir =  str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
            $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
            $core = $core[0];
            $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
            $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
            $base_url = sprintf( $tmplt, $http, $hostname, $end );
        }
        else $base_url = 'http://localhost/';
        if ($parse) {
            $base_url = parse_url($base_url);
            if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';
        }
        return $base_url;
    }
}

它具有漂亮的回报,例如:

// A URL like http://stackoverflow.com/questions/189113/how-do-i-get-current-page-full-url-in-php-on-a-windows-iis-server:
echo base_url();    // Will produce something like: http://stackoverflow.com/questions/189113/
echo base_url(TRUE);    // Will produce something like: http://stackoverflow.com/
echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE); //Will produce something like: http://stackoverflow.com/questions/
// And finally:
echo base_url(NULL, NULL, TRUE);
// Will produce something like:
//      array(3) {
//          ["scheme"]=>
//          string(4) "http"
//          ["host"]=>
//          string(12) "stackoverflow.com"
//          ["path"]=>
//          string(35) "/questions/189113/"
//      }

大家都忘了http_build_url?

http_build_url($_SERVER['REQUEST_URI']);

当没有参数传递给http_build_url时,它将自动采用当前 URL。我希望REQUEST_URI也包括在内,尽管似乎需要包含GET参数。

上面的示例将返回完整的 URL。

我使用了以下代码,并且得到了正确的结果...

<?php
    function currentPageURL() {
        $curpageURL = 'http';
        if ($_SERVER["HTTPS"] == "on") {
            $curpageURL.= "s";
        }
        $curpageURL.= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $curpageURL.= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } 
        else {
            $curpageURL.= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
        return $curpageURL;
    }
    echo currentPageURL();
?>

在我的 apache 服务器中,这为我提供了您正在寻找的确切格式的完整 URL:

$_SERVER["SCRIPT_URI"]

反向代理支持!

更坚固一点的东西。注意它仅适用于5.3或更高。

/*
 * Compatibility with multiple host headers.
 * Support of "Reverse Proxy" configurations.
 *
 * Michael Jett <mjett@mitre.org>
 */
function base_url() {
    $protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] 
              ?: @$_SERVER['REQUEST_SCHEME']
              ?: ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") ? "https" : "http");
    $port = @intval($_SERVER['HTTP_X_FORWARDED_PORT'])
          ?: @intval($_SERVER["SERVER_PORT"])
          ?: (($protocol === 'https') ? 443 : 80);
    $host = @explode(":", $_SERVER['HTTP_HOST'])[0]
          ?: @$_SERVER['SERVER_NAME']
          ?: @$_SERVER['SERVER_ADDR'];
    // Don't include port if it's 80 or 443 and the protocol matches
    $port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;
    return sprintf('%s://%s%s/%s', $protocol, $host, $port, @trim(reset(explode("?", $_SERVER['REQUEST_URI'])), '/'));
}