Skip to content

Instantly share code, notes, and snippets.

@ramondeklein
Created November 29, 2014 10:12
Show Gist options
  • Save ramondeklein/ef6c955b12ee09297cf8 to your computer and use it in GitHub Desktop.
Save ramondeklein/ef6c955b12ee09297cf8 to your computer and use it in GitHub Desktop.
Powershell HTTP(S) redirector
# This Powershell script can be used on a server to redirect HTTP/HTTPS
# traffic to different sources. Make sure your DNS routes the requests
# for the source URLs to this server. It automatically forwards the URL
# to the destination server without altering the rest of the URL.
#
# You can use multiple mappings. Of course the 'source' should be
# unique, but the destination can occur multiple times.
#
# Make sure PowerShell is allowed to run this script. You might need to
# change PowerShell's policy by running the following command as admin:
#
# PS C:> Set-ExecutionPolicy RemoteSigned
#
# I would advise not to run this script as Administrator, but as a uwer
# with restricted permission (in production use). You might need to authorize
# the user to handle specific HTTP(S) URLs. Refer to http://bit.ly/1Crn0xz
# for more information how to do this.
#
# Script written by Nov 2014 by Ramon de Klein (mail@ramondeklein.nl).
# Use and alter as you please.
$map = @{
# Source -> Destination
"http://localhost:8888/" = "http://www.microsoft.com/"
#"http://www.example.com/" = "https://example.com/"
#"https://www.example.com/" = "https://example.com/"
#"http://example.com/" = "https://example.com/"
#"http://blog.example.com/" = "https://example.com/blog/"
#"https://blog.example.com/" = "https://example.com/blog/"
}
# Setup the HTTP listener and start it
$listener = New-Object System.Net.HttpListener
$map.Keys | % {
# Listen on each source URL
Write-Host "- Redirect $_ to" $map.Item($_)
$listener.Prefixes.Add($_)
}
$listener.Start()
while ($listener.IsListening)
{
# Obtain HTTP context
$context = $listener.GetContext()
# Determine the request URL
$url = $context.Request.Url.ToString()
# Process the URL mappings
$map.Keys | % { $url = $url.Replace($_, $map.Item($_)) }
# Create a HTTP 301 (permanent redirect) response
$response = $context.Response
$response.StatusCode = 301
$response.AddHeader("Location", $url)
$response.Close()
# Log the redirect
Write-Host "> Redirecting to $url"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment