Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Last active November 28, 2022 16:09
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 JohnLBevan/13b610d8d12ede536e12118ebbeff565 to your computer and use it in GitHub Desktop.
Save JohnLBevan/13b610d8d12ede536e12118ebbeff565 to your computer and use it in GitHub Desktop.
Shows all the redirects which occur when hitting a given URI. Useful for checking how HTTP301 / HTTP302 / HTTP307 rules are configured. `Hostname` parameter allows us to handle cases where DNS doesn't match the hostname on our listener; useful for testing pre-go-live without updating your hosts file.
function Get-HttpUrlRedirects {
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$Url
,
[Parameter()]
[AllowNull()]
[AllowEmptyString()]
[string]$Hostname
)
$request = [System.Net.HttpWebRequest][System.Net.WebRequest]::Create($Url)
if (![string]::IsNullOrWhitespace($Hostname)) {
$request.Headers.Add("Host",$HostName)
}
$request.AllowAutoRedirect = $false
$request.UseDefaultCredentials = $true
try {
$response = $request.GetResponse()
$statusCode = $response.StatusCode.value__
([PSCustomObject]@{
Url = $Url
StatusCode = $statusCode
})
if (($statusCode -ge 300) -and ($statusCode -lt 400)) {
$redirectUri = $response.Headers['Location']
$redirectUri = [uri]::new($response.ResponseUri, $redirectUri).AbsoluteUri # ensure we correctly handle relative URIs too
Write-Verbose "Redirecting to [$redirectUri]"
Get-HttpUrlRedirects -Url $redirectUri
}
# } catch { # currently non need to catch / handle exceptions... but if there is a requirement this post has more info: https://stackoverflow.com/a/692369/361842
} finally {
$response.Dispose()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment