Build a redirection watchlist: chains, loops, mobile vs desktop parity, and hreflang…
- User
Build a redirection watchlist: chains, loops, mobile vs desktop parity, and hreflang integrity.
Assistant
Build a redirection watchlist: chains, loops, mobile vs desktop parity, and hreflang integrity.
The user wants to build a "redirection watchlist" that covers four specific areas:
The user is asking for a "build," implying they need a framework, a checklist, or a script/methodology to monitor these things.
Target Audience: SEO professionals, web developers, site reliability engineers. Tone: Technical, actionable, structured.
Plan:
Self-Correction/Refinement on Hreflang:
The prompt asks for "hreflang integrity" in a redirection watchlist.
Interpretation: If I have an hreflang tag x pointing to y, and y redirects to z, that is bad. Hreflang should point to z.
Also: If the current page is A, and it has hreflang pointing to B, does B redirect back to A (incorrectly) or serve content?
Script Logic:
Let's build the response:
requests and BeautifulSoup.Script specifics:
requests.Session to handle cookies if needed, but standard requests.get is fine.allow_redirects=False is better for manual tracking to detect meta refreshes or JS redirects, but allow_redirects=True with history inspection is standard for HTTP chains. I'll use allow_redirects=True but inspect response.history.url in response.history.Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) vs standard desktop.Hreflang in script: This adds significant complexity to a simple redirection script. I will implement a check: "Does the final URL match the expected hreflang target?" OR "Does the destination page return a 200?" Actually, "Hreflang Integrity" in a redirect context often means: "Do not redirect a URL that is the target of an hreflang tag." I will stick to checking if the final destination creates a conflict (e.g., different language than expected) or if the input URL is being used as an hreflang target elsewhere (requires crawling). For this script, I will check if the redirected URL has valid self-referencing tags, which is a common integrity check.
Let's focus on the 4 specific points requested.
len(response.history) > 1any(url in h.url for h in response.history)desktop_response.url != mobile_response.urlen-us hreflang?).I will structure the answer as a Technical Specification & Script.
Structure:
Refining the Hreflang check:
A common error is redirecting a URL that is referenced in an hreflang tag.
Since I cannot crawl the whole web to see what points to the URL, I will check:
Let's write the code mentally first.
check_url(url):
len(history) > 1.desktop.url != mobile.url.link rel='alternate' hreflang='x'. Check if it points to itself.This seems complete. I will produce the output. Building a redirection watchlist requires monitoring HTTP headers and HTML payloads across different user agents and comparing them against your sitemap or crawl list.
Here is a comprehensive framework and a Python script to build a Redirection Watchlist that specifically targets Chains, Loops, Mobile/Desktop Parity, and Hreflang Integrity.
Before scripting, we define the rules for the watchlist:
Length of redirect history > 1.Current URL exists in redirect history.Final Desktop URL != Final Mobile URL (ignoring protocol/http vs https) OR Desktop Status != Mobile Status.en-gb pointing to it, and it redirects, the target must handle that traffic.This script uses requests to fetch headers and BeautifulSoup to parse HTML for hreflang tags. It outputs a CSV report suitable for a monitoring dashboard.
Prerequisites:
pip install requests beautifulsoup4 pandas
Once you run the script (or implement this logic in a cloud function), your CSV/Dashboard should highlight the following columns:
Chain LengthChain Length > 1.Is LoopYes.200 OK without redirecting, or points to a different endpoint.M/M Parity!= Match./product-a but mobile redirects to /product-b (or a 404), Google will likely index the Mobile version (or the error), causing desktop ranking drops.Hreflang IntegrityWarning or Error./fr/page to /en/page, but the /en/page does not have hreflang="fr" pointing back or self-reference hreflang="en", you dilute your international signals.<link rel="alternate" hreflang="x" href="..."> tags.import requests
from bs4 import BeautifulSoup
import pandas as pd
from urllib.parse import urlparse
# Configuration
USER_AGENT_DESKTOP = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
USER_AGENT_MOBILE = "Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1"
TIMEOUT = 10
def get_redirect_chain(url, user_agent):
"""
Follows redirects and returns the chain history, status, and final HTML.
"""
headers = {"User-Agent": user_agent}
session = requests.Session()
try:
response = session.get(url, headers=headers, timeout=TIMEOUT, allow_redirects=True)
# Build the chain list
history_urls = [r.url for r in response.history]
history_urls.append(response.url)
# Remove duplicates (handling loops, though requests usually stops infinite loops)
# We check if the final URL is already in history (indicating a loop or weird settling)
return {
"chain": history_urls,
"status_code": response.status_code,
"final_url": response.url,
"html": response.text,
"error": None
}
except requests.RequestException as e:
return {
"chain": [url],
"status_code": 0,
"final_url": url,
"html": "",
"error": str(e)
}
def check_hreflang_integrity(html, final_url):
"""
Checks if the final page has a self-referencing hreflang.
This is a basic integrity check: "Did we land on a page that claims what it is?"
"""
if not html: return "Error: No HTML"
soup = BeautifulSoup(html, 'html.parser')
links = soup.find_all('link', rel='alternate', hreflang=True)
# Extract just the URL paths for comparison to ignore http/https diffs
final_path = urlparse(final_url).path
for link in links:
target = link.get('href')
if urlparse(target).path == final_path:
# Found self-reference
return f"OK ({link.get('hreflang')})"
return "Warning: No Self-Referencing Hreflang found"
def analyze_url(input_url):
print(f"Analyzing: {input_url}")
# 1. Desktop Crawl
desk_data = get_redirect_chain(input_url, USER_AGENT_DESKTOP)
# 2. Mobile Crawl
mob_data = get_redirect_chain(input_url, USER_AGENT_MOBILE)
# --- ANALYSIS ---
# Issue 1: Chains
# If history has more than 1 item (Start -> Step 1 -> Final), it's a chain.
chain_length = len(desk_data['chain']) - 1
is_chained = "Yes" if chain_length > 1 else "No"
# Issue 2: Loops
# Check if the final URL appears in the history (excluding the final position itself)
# Or if any URL in history repeats.
history_paths = [urlparse(u).path for u in desk_data['chain']]
is_loop = "Yes" if len(history_paths) != len(set(history_paths)) else "No"
# Issue 3: Mobile vs Desktop Parity
# We compare the PATH, ignoring domain differences (e.g. m.example.com vs www.example.com)
# unless you explicitly want strict domain matching.
desk_path = urlparse(desk_data['final_url']).path
mob_path = urlparse(mob_data['final_url']).path
parity_status = "Match"
if desk_path != mob_path:
parity_status = "Mismatch (Content Divergence)"
elif desk_data['status_code'] != mob_data['status_code']:
parity_status = f"Status Mismatch (D:{desk_data['status_code']} M:{mob_data['status_code']})"
# Issue 4: Hreflang Integrity
# Check the destination page for valid hreflang signals
hreflang_status = check_hreflang_integrity(desk_data['html'], desk_data['final_url'])
return {
"Input URL": input_url,
"Chain Length": chain_length,
"Is Chain": is_chained,
"Is Loop": is_loop,
"Final Desktop": desk_data['final_url'],
"Final Mobile": mob_data['final_url'],
"M/M Parity": parity_status,
"Hreflang Integrity": hreflang_status,
"Status": desk_data['status_code']
}
# --- EXECUTION BLOCK ---
# 1. Load your watchlist (replace this with your sitemap or list of critical URLs)
urls_to_watch = [
"https://example.com/",
"https://example.com/old-page-redirect",
"https://example.com/loop-example"
]
results = []
for url in urls_to_watch:
# Basic validation to ensure URL has scheme
if not url.startswith("http"):
url = "https://" + url
results.append(analyze_url(url))
# Export to CSV for the "Watchlist" Dashboard
df = pd.DataFrame(results)
df.to_csv("redirection_watchlist_report.csv", index=False)
print("Watchlist Report Generated.")