Self-referencing URLs

What is the most reliable, general way to build a self-referencing URL? In other words, I want to generate the http://www.site.com [: port] part of the URL that the user's browser hits. I am using PHP running under Apache.

A few complications:

  • Relying on $ _SERVER ["HTTP_HOST"], this is dangerous because it looks like it is directly from the HTTP Host header that someone can fake.

  • There may or may not be virtual hosts.

  • There may be a port specified using the Apache Port directive, but it may not be the port specified by the user if it is located behind a load balancer or proxy.

  • A port cannot be part of a URL. For example, 80 and 443 are usually omitted.

  • PHP $ _SERVER ["HTTPS"] does not always give a reliable value, especially if you are behind a load balancer or proxy.

  • Apache has a UseCanonicalName directive that affects the values ​​of the SERVER_NAME and SERVER_PORT environment variables. We can assume that this is included if it helps.

+3
source share
6 answers

The most reliable way is to provide it yourself.

, . , -. , , -. , .., , HTTP- , , .

, .: -)

+1

, - :

$protocol = 'http';

if ( (!empty($_SERVER['HTTPS'])) || ($_SERVER['HTTPS'] == 'off') ) {
    $protocol = 'https';
    if ($_SERVER['SERVER_PORT'] != 443)
        $port = $_SERVER['SERVER_PORT'];
} else if ($_SERVER['SERVER_PORT'] != 80) {
    $port = $_SERVER['SERVER_PORT'];
}
// Server name is going to be whatever the virtual host name is set to in your configuration
$address = $protocol . '://' . $_SERVER['SERVER_NAME'];
if (!empty($port))
    $address .= ':' . $port
$address .= $_SERVER['REQUEST_URI'];
// Optional, if you want the query string intact
if (!empty($_SERVER['QUERY_STRING']))
    $address .= '?' . $_SERVER['QUERY_STRING'];

, PHP.

+2

, - url - . $_SERVER ['HTTP_HOST'] , .

define('SITE_URL', $_SERVER['HTTP_HOST']);

:

define('SITE_URL', 'http://foo.bar.com:8080/');
+2

$_ SERVER [ "HTTP_HOST" ], , , , .

, , , , .

0

, $_SERVER ['HTTP_HOST'] , DNS. , , , IP-.

http://www.php.net/manual/en/function.gethostbyname.php

Peusudo :

define('SITEHOME', in_array(gethostbyname($_SERVER['HTTP_HOST']), array(... valid IP's))) 
? $_SERVER['HTTP_HOST']
: 'default_hostname';
0

why { , http:///host: port/, URL-} URL-

http://xxx:yy/zzz/fff/

..//whatever.jpg { http://xxx: yy/zzz/graphics/whatever.jpg

/zzz/graphics/whatever.jpg { }

:

0

Source: https://habr.com/ru/post/1702388/


All Articles