Last active
September 20, 2019 14:17
-
-
Save kimbtech/1ee0a9609d0852fcfb91eafb1a78782e to your computer and use it in GitHub Desktop.
Dynamic Reverse Proxy Using NGINX and PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
# nginx conf. | |
# proxy | |
# /proxy/<hostname>/?<url> | |
# url has to be written using ip, no hostname, cause no dns lookup is done! | |
location ~* "^/proxy/([^/]*)/?.*$" { | |
internal; | |
proxy_pass $args; | |
proxy_set_header Host $1; | |
proxy_buffering off; | |
proxy_connect_timeout 5s; | |
proxy_redirect https://$1/ /stream.php?url=https://$1/; | |
proxy_redirect http://$1/ /stream.php?url=http://$1/; | |
} | |
*/ | |
error_reporting(E_ALL); | |
define('ALLOW_LOCAL_PROXY', true); | |
// station known? | |
if( isset($_GET['url']) ){ | |
$url = $_GET['url']; | |
if( !empty($url) ){ | |
$url = filter_var( $url, FILTER_SANITIZE_URL, FILTER_FLAG_HOST_REQUIRED | FILTER_FLAG_SCHEME_REQUIRED); //clean url | |
// get hostname and url parts before and after | |
$matches = array(); | |
$matchok = preg_match( '/^(https?:\/\/)([^\/]+\.?[a-zA-Z]+)((?::[0-9]+)?(?:\/.*)?)$/', $url, $matches ); // get host | |
$host = $matches[2]; | |
// host ok? | |
if( $matchok === 1 ){ | |
// check ip address | |
$ip = gethostbyname( $host ); | |
// create url using ip | |
$url = $matches[1] . $ip . $matches[3]; | |
// allow only external ips | |
if( ALLOW_LOCAL_PROXY || filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false ){ | |
//let nginx do the rest | |
header("X-Accel-Redirect: /proxy/". $host ."/?" . $url ); | |
die(); | |
} | |
} | |
} | |
} | |
?> | |
<html> | |
<body> | |
<form action="" method="get"> | |
<input type="url" name="url"> | |
<input type="submit" value="Öffnen"> | |
</form> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment