Skip to content

Instantly share code, notes, and snippets.

@kimbtech
Last active September 20, 2019 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kimbtech/1ee0a9609d0852fcfb91eafb1a78782e to your computer and use it in GitHub Desktop.
Save kimbtech/1ee0a9609d0852fcfb91eafb1a78782e to your computer and use it in GitHub Desktop.
Dynamic Reverse Proxy Using NGINX and PHP
<?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