Preventing Open Redirects
What you'll learn: How to securely validate and control redirects so attackers can't send users to malicious sites.
Now that you understand how open redirects work and their impact, let's focus on stopping them at the source.
The Core Defense Strategy
Preventing open redirects boils down to three principles: never trust redirect destinations, validate rigorously, and use safe patterns. Think of it like a bouncer at a club — you need a strict list of approved destinations, not just a vague "looks okay" check.
1. Allowlist Approved Destinations
The strongest defense is maintaining an allowlist (whitelist) of permitted redirect targets:
ALLOWED_REDIRECTS = [
'https://example.com/dashboard',
'https://example.com/profile',
'https://example.com/settings'
]
def safe_redirect(target):
if target in ALLOWED_REDIRECTS:
return redirect(target)
else:
return redirect('/default') # Safe fallback
For domains rather than exact URLs, validate the scheme and host:
from urllib.parse import urlparse
ALLOWED_DOMAINS = ['example.com', 'app.example.com']
def is_safe_domain(url):
parsed = urlparse(url)
return (parsed.scheme in ['http', 'https'] and
parsed.netloc in ALLOWED_DOMAINS)
2. Use Indirect References
Instead of accepting URLs directly, use mapped tokens:
REDIRECT_MAP = {
'dashboard': '/user/dashboard',
'profile': '/user/profile'
}
# User sees: ?next=dashboard (not the actual URL)
target = REDIRECT_MAP.get(request.args.get('next'), '/default')
3. Validate Relative Paths Only
If you must accept user input, reject absolute URLs entirely and only allow relative paths:
def is_relative_path(url):
return url.startswith('/') and not url.startswith('//')
Key Takeaway: Prevent open redirects by using allowlists of approved destinations, validating both scheme and host for external redirects, and preferring indirect reference tokens over accepting raw URLs from user input.