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

时间:2008-10-09 20:39:50

标签: php iis

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

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

我无法弄清楚如何抓取网址的/post-title/部分。

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

15 个答案:

答案 0 :(得分:135)

也许,因为你在IIS下,

$_SERVER['PATH_INFO']

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

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

答案 1 :(得分:63)

$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;

答案 2 :(得分:36)

对于Apache:

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


Herman评论说,您也可以使用HTTP_HOST代替SERVER_NAME。有关完整讨论,请参阅this related question。简而言之,使用其中任何一个都可以。这是“主机”版本:

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


为偏执狂/为何重要

通常,我在ServerName中设置了VirtualHost,因为我希望 成为网站的canonical形式。 $_SERVER['HTTP_HOST']是根据请求标头设置的。如果服务器响应该IP地址上的任何/所有域名,则用户可以欺骗标题,或者更糟糕的是,有人可能将DNS记录指向您的IP地址,然后您的服务器/网站将提供具有动态的网站建立在错误网址上的链接。如果您使用后一种方法,则还应配置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的方法时结束的人提供第一行代码:)

答案 3 :(得分:11)

$_SERVER['REQUEST_URI']无法在IIS上运行,但我确实发现了这一点: http://neosmart.net/blog/2006/100-apache-compliant-request_uri-for-iis-and-windows/听起来很有希望。

答案 4 :(得分:9)

使用此类可以获取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;

答案 5 :(得分:7)

添加:

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函数。

答案 6 :(得分:5)

我使用以下函数获取当前的完整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;
}

答案 7 :(得分:4)

REQUEST_URI由Apache设置,因此您无法通过IIS获取它。尝试在$ _SERVER上执行var_dump或print_r,看看那里有你可以使用的值。

答案 8 :(得分:3)

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

来获取它

答案 9 :(得分:2)

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

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

答案 10 :(得分:1)

哦,片段的乐趣!

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/"
//      }

答案 11 :(得分:0)

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

<?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();
?>

答案 12 :(得分:0)

每个人都忘了http_build_url

http_build_url($_SERVER['REQUEST_URI']);

如果没有参数传递给http_build_url,它将自动采用当前网址。我希望也包含REQUEST_URI,但为了包含GET参数似乎需要它。

以上示例将返回完整的网址。

答案 13 :(得分:0)

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

$_SERVER["SCRIPT_URI"]

答案 14 :(得分:0)

反向代理支持!

更健壮的东西。 注意它仅适用于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'])), '/'));
}