Audit HTTP Security Headers Across a Sitemap with Python (Standard Library Only): Missing HSTS, CSP and Cookie Flags
Most online header checkers test one URL, usually the homepage. That is where the theme or the CDN sets everything correctly.
The gaps sit elsewhere: a blog that still runs on an older install under /blog, a booking page from a plugin that sets its own cookie, a landing page served by a different app. If you look after websites for clients (a small agency with a dozen local business sites, say), you want one run per site that checks every page the client cares about and tells you where the headers differ.
This post builds that check in Python using only the standard library (urllib, ssl, xml.etree, csv, concurrent.futures). You give it a sitemap. It fetches every URL, probes the plain-HTTP version of each one, and flags:
- pages where plain HTTP serves the page instead of redirecting to HTTPS
- missing or short-lived
Strict-Transport-Security - missing
Content-Security-Policy, or a policy that allows'unsafe-inline'scripts - no protection against framing (no
frame-ancestorsand no usableX-Frame-Options) - missing
X-Content-Type-Options: nosniff, a missing orunsafe-urlReferrer-Policy, and a missingPermissions-Policy - the legacy
X-XSS-Protection: 1filter switched on - headers that announce your stack and version (
Server: Apache/2.4.41,X-Powered-By: PHP/7.4.33) - cookies without
Secure,HttpOnlyorSameSite - security headers that are set on some pages but not others
It writes a CSV with one row per issue and prints a summary. Every output below comes from a real run against a small fictional test site on localhost, which you can rebuild from the code in this post.
Sources opened on 24 Nov 2026: MDN's reference pages for Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, X-XSS-Protection and Set-Cookie, and the OWASP Secure Headers Project with its published lists of headers to add and headers to remove (both showing "last_update_utc": "2026-11-23"). The test site ("Hollis Street Dental") is fictional and runs on localhost. Appie free-tool descriptions are as of 24 Nov 2026, checked on the tool's page that day. Disclosure: Appie.run publishes this article. One free tool mentioned near the end is ours. The script does not depend on it.
What this is (and is not)
Security headers are instructions from the server to the browser: only use HTTPS for this host, do not let other sites put this page in a frame, do not guess file types, send less referrer data. They are cheap to set and easy to lose when a site has more than one moving part.
This script checks whether those headers are present and sensibly configured on each page. It is not a vulnerability scanner, it does not test your forms or logins, and a clean report does not mean a site is secure. Treat it as a hygiene check you can run on every client site each month.
What the references say
HSTS. MDN: the header "informs browsers that the host should only be accessed using HTTPS, and that any future attempts to access it using HTTP should automatically be upgraded to HTTPS."
Two details matter for an audit. First, "Browsers ignore the header if sent over HTTP," so it only counts on HTTPS responses. Second, for preloading, "the max-age directive must be at least 31536000 (1 year)." The script uses one year as its threshold. OWASP's recommended value is max-age=63072000; includeSubDomains (two years).
Framing. MDN on X-Frame-Options: if it is not sent and the site has no other way to restrict embedding, "such as the frame-ancestors CSP directive," then "the browser will allow other sites to embed this document." DENY and SAMEORIGIN are the valid values. ALLOW-FROM "is an obsolete directive. Modern browsers that encounter response headers with this directive will ignore the header completely." So the script treats ALLOW-FROM as no protection.
nosniff. MDN on X-Content-Type-Options: "Site security testers usually expect this header to be set." With nosniff, the browser blocks scripts and stylesheets whose MIME type does not match, and uses the declared Content-Type for everything else.
Referrer-Policy. MDN describes unsafe-url as sending the origin, path and query string for every request, regardless of security. That can leak URLs with tokens or search terms to third parties, including over plain HTTP. OWASP's recommended value is no-referrer; many sites use strict-origin-when-cross-origin.
X-XSS-Protection. MDN marks it non-standard and warns that "in some cases, X-XSS-Protection can create XSS vulnerabilities in otherwise safe websites." It recommends using Content-Security-Policy instead. The script flags any value that turns the filter on (1, 1; mode=block).
Headers to remove. OWASP keeps a list of response headers that only describe your stack, including Server, X-Powered-By, X-AspNet-Version and X-Generator. The script checks a short subset and only flags Server when it contains a version number.
Cookies. MDN's Set-Cookie reference documents the Secure, HttpOnly and SameSite attributes. The script flags cookies that lack any of them, with one caveat covered later: a cookie that your own JavaScript needs to read cannot be HttpOnly.
How the audit works
- Read the sitemap (and any child sitemaps in a sitemap index).
- Fetch each URL over HTTPS, following redirects, and keep the response headers.
- Request the
http://version of the same URL without following redirects. A301/308to anhttps://URL is good; a200means plain HTTP serves the page. - Run each page's headers through the checks and give every finding a severity (high, medium, low, info).
- Count which security headers appear on which pages, and list headers that are present on some pages but missing on others. That pattern usually means a second app, theme or server is serving part of the site.
- Write a CSV sorted by severity and print a summary.
The script
Save this as security_headers_audit.py. It needs Python 3.9 or newer and nothing else.
#!/usr/bin/env python3
"""Audit HTTP security headers for every URL in a sitemap. Standard library only. Usage: python3 security_headers_audit.py https://example.com/sitemap.xml --csv headers_report.csv """
import argparse , csv , re , ssl , sys , urllib . error , urllib . request
import xml . etree . ElementTree as ET
from collections import defaultdict
from concurrent . futures import ThreadPoolExecutor
from urllib . parse import urlsplit , urlunsplit
UA = "security-headers-audit/1.0 (+https://dev.to/appierun_66)"
NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
ONE_YEAR = 31536000
# Headers that only describe your stack. Trimmed from OWASP's "headers to remove" list.
LEAKY = [ "server" , "x-powered-by" , "x-aspnet-version" , "x-aspnetmvc-version" , "x-generator" , "x-cms" ]
SEVERITY_ORDER = { "high" : 0 , "medium" : 1 , "low" : 2 , "info" : 3 }
class NoRedirect ( urllib . request . HTTPRedirectHandler ) :
def redirect_request ( self , * args , ** kwargs ) :
return None
def make_opener ( ctx , follow = True ) :
handlers = [ urllib . request . HTTPSHandler ( context = ctx ) ]
if not follow :
handlers . append ( NoRedirect ( ) )
return urllib . request . build_opener ( * handlers )
def fetch ( opener , url , timeout = 15 ) :
"""Return (status, final_url, headers). headers is a list of (name, value) pairs."""
req = urllib . request . Request ( url , headers = { "User-Agent" : UA } )
try :
with opener . open ( req , timeout = timeout ) as r :
return r . status , r . geturl ( ) , r . headers . items ( )
except urllib . error . HTTPError as e :
return e . code , url , e . headers . items ( ) if e . headers else [ ]
except Exception as e :
return None , url , [ ( "x-audit-error" , str ( e ) [ : 120 ] ) ]
def sitemap_urls ( opener , url , seen = None ) :
seen = seen or set ( )
if url in seen :
return [ ]
seen . add ( url )
req = urllib . request . Request ( url , headers = { "User-Agent" : UA } )
with opener . open ( req , timeout = 20 ) as r :
root = ET . fromstring ( r . read ( ) )
if root . tag == NS + "sitemapindex" :
out = [ ]
for loc in root . iter ( NS + "loc" ) :
out += sitemap_urls ( opener , loc . text . strip ( ) , seen )
return out
return [ loc . text . strip ( ) for loc in root . iter ( NS + "loc" ) ]
def http_variant ( url , http_port = None ) :
parts = urlsplit ( url )
host = parts . hostname
netloc = f "{host}:{http_port}" if http_port else host
return urlunsplit ( ( "http" , netloc , parts . path or "/" , parts . query , "" ) )
def check_page ( url , headers , http_status , http_location ) :
"""Return a list of (issue, severity, detail)."""
issues = [ ]
h = defaultdict ( list )
for k , v in headers :
h [ k . lower ( ) ] . append ( v . strip ( ) )
first = lambda name : h [ name ] [ 0 ] if h . get ( name ) else None
https = url . startswith ( "https://" )
# 1. HTTPS and the plain-HTTP door
if not https :
issues . append ( ( "not_https" , "high" , "page URL in sitemap is http://" ) )
elif http_status is not None :
if http_status in ( 301 , 302 , 307 , 308 ) :
if not ( http_location or "" ) . startswith ( "https://" ) :
issues . append ( ( "http_redirects_elsewhere" , "medium" , f "http -> {http_location}" ) )
elif http_status == 200 :
issues . append ( ( "http_no_redirect" , "high" , "plain HTTP serves the page with 200" ) )
# 2. HSTS
hsts = first ( "strict-transport-security" )
if https :
if not hsts :
issues . append ( ( "hsts_missing" , "high" , "" ) )
else :
m = re . search ( r "max-age\s*=\s*\"?(\d+)" , hsts , re . I )
age = int ( m . group ( 1 ) ) if m else 0
if age < ONE_YEAR :
issues . append ( ( "hsts_short_max_age" , "medium" , f "max-age={age}" ) )
# 3. CSP
csp = first ( "content-security-policy" )
if not csp :
ro = " (only Content-Security-Policy-Report-Only is set)" if first ( "content-security-policy-report-only" ) else ""
issues . append ( ( "csp_missing" , "medium" , ro . strip ( ) ) )
directives = { }
else :
directives = { }
for part in csp . split ( ";" ) :
bits = part . strip ( ) . split ( )
if bits :
directives [ bits [ 0 ] . lower ( ) ] = [ b . lower ( ) for b in bits [ 1 : ] ]
scripts = directives . get ( "script-src" , directives . get ( "default-src" , [ ] ) )
has_nonce_or_hash = any ( s . startswith ( ( "'nonce-" , "'sha256-" , "'sha384-" , "'sha512-" ) ) for s in scripts )
if "'unsafe-inline'" in scripts and not has_nonce_or_hash :
issues . append ( ( "csp_unsafe_inline_scripts" , "medium" , "script-src allows 'unsafe-inline'" ) )
if "'unsafe-eval'" in scripts :
issues . append ( ( "csp_unsafe_eval" , "low" , "script-src allows 'unsafe-eval'" ) )
# 4. Framing (clickjacking)
xfo = ( first ( "x-frame-options" ) or "" ) . upper ( )
has_fa = "frame-ancestors" in directives
if xfo . startswith ( "ALLOW-FROM" ) :
issues . append ( ( "xfo_allow_from_obsolete" , "low" , "browsers ignore ALLOW-FROM" ) )
if not has_fa and xfo not in ( "DENY" , "SAMEORIGIN" ) :
issues . append ( ( "framing_unprotected" , "medium" , "no frame-ancestors and no usable X-Frame-Options" ) )
# 5. Smaller headers
if ( first ( "x-content-type-options" ) or "" ) . lower ( ) != "nosniff" :
issues . append ( ( "nosniff_missing" , "low" , "" ) )
rp = ( first ( "referrer-policy" ) or "" ) . lower ( )
if not rp :
issues . append ( ( "referrer_policy_missing" , "low" , "browser default applies" ) )
elif "unsafe-url" in rp :
issues . append ( ( "referrer_policy_unsafe_url" , "medium" , "full URL sent to every site, including over http" ) )
if not first ( "permissions-policy" ) :
issues . append ( ( "permissions_policy_missing" , "info" , "" ) )
xxp = first ( "x-xss-protection" )
if xxp and xxp . strip ( ) . startswith ( "1" ) :
issues . append ( ( "x_xss_protection_enabled" , "low" , f "'{xxp}' (MDN: use CSP; send 0 or nothing)" ) )
# 6. Headers that describe your stack
for name in LEAKY :
for v in h . get ( name , [ ] ) :
if name != "server" or re . search ( r "\d" , v ) :
issues . append ( ( "stack_header" , "low" , f "{name}: {v}" ) )
# 7. Cookies
for c in h . get ( "set-cookie" , [ ] ) :
cname = c . split ( "=" , 1 ) [ 0 ]
attrs = c . lower ( )
missing = [ a for a , key in ( ( "Secure" , "; secure" ) , ( "HttpOnly" , "; httponly" ) , ( "SameSite" , "samesite=" ) ) if key not in attrs ]
if missing :
issues . append ( ( "cookie_missing_flags" , "medium" , f "{cname}: missing {', '.join(missing)}" ) )
if first ( "x-audit-error" ) :
issues . append ( ( "fetch_error" , "high" , first ( "x-audit-error" ) ) )
return issues
def main ( ) :
ap = argparse . ArgumentParser ( description = __doc__ , formatter_class = argparse . RawDescriptionHelpFormatter )
ap . add_argument ( "sitemap" )
ap . add_argument ( "--csv" , default = "headers_report.csv" )
ap . add_argument ( "--cafile" , help = "extra CA bundle, e.g. for a self-signed test server" )
ap . add_argument ( "--http-port" , type = int , help = "port for the plain-HTTP probe (default 80)" )
ap . add_argument ( "--workers" , type = int , default = 4 )
args = ap . parse_args ( )
ctx = ssl . create_default_context ( cafile = args . cafile ) if args . cafile else ssl . create_default_context ( )
follow , nofollow = make_opener ( ctx ) , make_opener ( ctx , follow = False )
urls = sitemap_urls ( follow , args . sitemap )
def audit ( url ) :
status , final , headers = fetch ( follow , url )
http_status , http_loc = None , None
if url . startswith ( "https://" ) :
s , _ , hh = fetch ( nofollow , http_variant ( url , args . http_port ) )
http_status = s
http_loc = dict ( ( k . lower ( ) , v ) for k , v in hh ) . get ( "location" )
return url , status , headers , check_page ( final , headers , http_status , http_loc )
with ThreadPoolExecutor ( args . workers ) as pool :
results = list ( pool . map ( audit , urls ) )
rows , by_issue , flagged = [ ] , defaultdict ( set ) , 0
present = defaultdict ( set )
for url , status , headers , issues in results :
for k , _ in headers :
present [ k . lower ( ) ] . add ( url )
if issues :
flagged += 1
for issue , sev , detail in issues :
by_issue [ ( issue , sev ) ] . add ( url )
rows . append ( { "url" : url , "status" : status , "issue" : issue , "severity" : sev , "de
Comments
No comments yet. Start the discussion.