Код:
<?php
# GAE-based webproxy server. V.4
# License: CC0 1.0
$host = "rutracker.org"; # translated host
$host_scheme = "http"; # protocol type: "http" or "https"
$encryption = false; # enable an encrypted connection to the proxy
$request = rawurldecode($_SERVER['REQUEST_URI']);
# stop bots
if ('/robots.txt' == $request) {
die("User-agent: *rnDisallow: /rn");
}
# forced on/off encryption
if ($_SERVER['HTTPS'] != ($encryption ? 'on' : 'off') {
http_response_code(301);
header('Location: ' . ($encryption ? 'https://' : 'http://') .
$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], true);
die();
}
# decode name of subdomain
if ($encryption) {
$subdomain = '';
$proxy_host = $_SERVER['HTTP_HOST'];
$a = explode('/', $request, 3);
if (strlen($a[1]) > 2 && '.' == $a[1][0]) {
$subdomain = substr($a[1], 1);
$request = '/' . $a[2];
}
} else {
$a = explode('.', $_SERVER['HTTP_HOST']);
$proxy_host = implode('.', array_slice($a, -3);
array_pop($a);
array_pop($a);
if (count($a) > 1 && 1 === preg_match('~^[0-9]+$~', $a[count($a) - 2]) {
$proxy_host = $a[count($a) - 2] . '.' . $proxy_host;
array_pop($a);
}
$a[count($a) - 1] = '';
$subdomain = implode('.', $a);
}
# translate browser headers
$headers = '';
foreach ($_SERVER as $name => $value) {
$a = explode('_', $name);
if (count($a) < 2 || $a[0] != 'HTTP' || $a[1] == 'X') continue;
array_shift($a);
$name = strtolower(implode('-', $a);
$headers .= $name . ': ' . str_replace($proxy_host, $host, $value) . "rn";
}
# send req to host
$context = stream_context_create([
'http' => [
'ignore_errors' => true,
'follow_location' => false,
'method' => $_SERVER['REQUEST_METHOD'],
'header' => $headers,
'timeout' => 30,
'content' => http_build_query($_POST)
]
]);
$url = $host_scheme . '://' . $subdomain . $host . $request;
$result = @file_get_contents($url, false, $context);
if (!isset($http_response_header) {
http_response_code(404);
syslog(LOG_WARNING, "Can not access to {$url}");
die("Proxy error. Can not access to {$url}");
}
# respond headers to browser
foreach ($http_response_header as $header_line) {
header(str_replace($host, $proxy_host, $header_line), false);
$a = preg_split('~[ :;,/\]+~', trim(strtolower($header_line);
if ('content-type' == $a[0]) $c_type = $a;
}
# convert links in the text content:
# "http://abc.def.example.com" -> "//abc.def.my-proxy.appspot.com"
#
# or for encrypted connections:
# "http://abc.def.example.com" -> "//my-proxy.appspot.com/.abc.def."
if (isset($c_type) && in_array($c_type[1], ['text', 'application']) &&
in_array($c_type[2], ['html', 'css', 'xml', 'xhtml+xml', 'javascript']) {
$result = preg_replace_callback(
'/(?<=[^:])(http:|https:|)(//)([a-z0-9-.]+.|)' . preg_quote($host) . '/is',
function ($m) {
global $proxy_host, $encryption;
return $encryption ?
"//{$proxy_host}" . ($m[3] ? '/.' . $m[3] : '') :
"//{$m[3]}{$proxy_host}";
},
$result);
}
echo $result;
# end of file