How to Enforce a Strict Referrer Policy in Python

Validate HTTP headers to enforce a strict same-origin Referrer policy, accepting only origin-only URLs or absent Referer values.

Easy Python 3.8+ Aug 9, 2026 Auth & security at scale 15 views 0 copies

Python code

23 lines
Python 3.8+
import re
from unittest.mock import patch

def strict_referrer_policy(headers):
    """Return True if Referer header is absent or strictly same-origin."""
    referer = headers.get("Referer")
    if referer is None:
        return True
    # Strict-Origin-When-Cross-Origin allows same-origin full URL
    # but here we demand same-origin only (no path or query)
    return bool(re.match(r"^https?://[^/]+$", referer))

if __name__ == "__main__":
    # Mock a strict browser that never sends Referer cross-origin
    with patch("builtins.input", return_value=""):
        test_headers = [
            {},  # no referer
            {"Referer": "https://example.com"},
            {"Referer": "https://example.com/page?q=1"},
            {"Referer": "https://other.com"},
        ]
        for headers in test_headers:
            print(f"{headers} -> {strict_referrer_policy(headers)}")

Output

stdout
{} -> True
{'Referer': 'https://example.com'} -> True
{'Referer': 'https://example.com/page?q=1'} -> False
{'Referer': 'https://other.com'} -> False

How it works

The strict_referrer_policy function checks if a Referer header is absent or matches a regex that only allows an origin URL (scheme, domain, optional port) with no path or query string. The regex ^https?://[^/]+$ ensures the Referring URL is exactly the origin, blocking any path, query, or fragment. The function returns True for same-origin requests and False for cross-origin or path-inclusive referrers, enforcing a strict policy. Using headers.get avoids KeyError and treats missing Referer as compliant. The unittest.mock.patch is used in the demo to simulate an empty input, though it's not essential to the core logic.

Common mistakes

  • Not accounting for missing Referer headers, which should be allowed in strict mode
  • Using a regex that permits paths like `https://example.com/page` as valid referrers
  • Forgetting to consider port numbers in the origin, which the regex handles correctly
  • Assuming case-insensitivity of the 'Referer' header name — use proper header parsing

Variations

  1. Use `urlparse` from `urllib.parse` to compare scheme and netloc instead of regex
  2. Implement a full Strict-Origin-When-Cross-Origin policy allowing same-origin URLs with paths

Real-world use cases

  • Validating incoming requests in a web framework to block CSRF attacks from cross-origin referrers.
  • Enforcing security headers compliance in a reverse proxy or API gateway.
  • Writing unit tests to verify that your server only accepts requests with strict origin-only referrers.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Auth & security at scale

Related tutorials and quizzes for this topic.