.htaccess Redirect Generator — Python source
Generate Apache .htaccess redirect rules from a simple editor: per-path redirects with 301, 302 or 308, plus force-HTTPS and www canonicalization blocks. Runs locally with a shareable link.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""htaccess-generator — Apache .htaccess Redirect Generator. Python port
(canonical TS: src/lib/htaccess-generator.ts; Go twin:
cli/htaccess-generator/htaccess-generator.go). Composes Apache directives
from validated rules: per-rule `Redirect <code> <from> <to>` lines (301/302/
308) plus optional force-HTTPS and www canonicalization blocks inside one
<IfModule mod_rewrite.c> wrapper (RewriteEngine On first, dots escaped in the
host conditions). Fixed section order — HTTPS block, canonical block, then
redirects — joined by a single blank line under the '# Generated by CosmoDev
— .htaccess' header (em dash). Validation runs in the TS order and the first
failure wins: from path (starts with '/', no whitespace), to target
(non-blank), code, duplicate from-paths, then the www options (wwwToApex/
apexToWww mutual exclusion, required bare domain, no protocol). No rules and
no flags is NOT an error — empty output, error None. Never raises — errors
travel in the result dict.
"""
import re
HEADER = "# Generated by CosmoDev — .htaccess"
_WS = re.compile(r"\s")
_PROTO = re.compile(r"^https?://")
_CODES = (301, 302, 308)
def generate_htaccess(rules, options=None):
"""Build .htaccess text. rules: [{'from', 'to', 'code'}]; options:
{force_https, www_to_apex, apex_to_www, domain}. Returns
{'output': str, 'error': str | None}."""
options = options or {}
seen = set()
for i, r in enumerate(rules):
f, t, code = r.get("from", ""), r.get("to", ""), r.get("code")
if not f.startswith("/") or _WS.search(f):
return {"output": "", "error": f'Rule {i + 1}: "from" must be a path starting with / (no spaces)'}
if not t.strip():
return {"output": "", "error": f'Rule {i + 1}: "to" is required'}
if code not in _CODES:
return {"output": "", "error": f"Rule {i + 1}: code must be 301, 302 or 308"}
if f in seen:
return {"output": "", "error": f'Duplicate "from" path: {f}'}
seen.add(f)
force_https = bool(options.get("force_https"))
www_to_apex = bool(options.get("www_to_apex"))
apex_to_www = bool(options.get("apex_to_www"))
domain = options.get("domain") or ""
if www_to_apex and apex_to_www:
return {"output": "", "error": "Pick one canonical direction: www→apex or apex→www"}
wants_www = www_to_apex or apex_to_www
if wants_www and not domain:
return {"output": "", "error": "A domain is required for www canonicalization"}
if domain and _PROTO.match(domain):
return {"output": "", "error": "Domain must be a bare host, without a protocol"}
sections = []
if force_https or wants_www:
inner = ["RewriteEngine On"]
if force_https:
inner += ["", "# Force HTTPS", "RewriteCond %{HTTPS} off",
"RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]"]
if wants_www and domain:
host = domain.replace(".", "\\.") # /\./g → '\\.'
inner += ["", "# Canonical: " + ("apex domain" if www_to_apex else "www domain")]
if www_to_apex:
inner += [f"RewriteCond %{{HTTP_HOST}} ^www\\.{host}$ [NC]",
f"RewriteRule ^ https://{domain}%{{REQUEST_URI}} [L,R=301]"]
else:
inner += [f"RewriteCond %{{HTTP_HOST}} ^{host}$ [NC]",
f"RewriteRule ^ https://www.{domain}%{{REQUEST_URI}} [L,R=301]"]
sections.append("<IfModule mod_rewrite.c>\n" + "\n".join(inner) + "\n</IfModule>")
if rules:
sections.append("\n".join(["# Redirects"] +
[f"Redirect {r['code']} {r['from']} {r['to']}" for r in rules]))
if not sections: # nothing to generate — empty output is NOT an error
return {"output": "", "error": None}
return {"output": "\n\n".join([HEADER] + sections) + "\n", "error": None}
# Example:
# generate_htaccess([{"from": "/old", "to": "/new", "code": 301}])["output"]
# → '# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n'
# generate_htaccess([], {"force_https": True, "apex_to_www": True, "domain": "example.com"})["error"]
# → None (output is the IfModule block: Force HTTPS first, then the canonical lines)
if __name__ == "__main__":
g = generate_htaccess
assert g([]) == {"output": "", "error": None}
assert g([{"from": "/old", "to": "/new", "code": 301}])["output"] == (
"# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n")
r = g([], {"force_https": True, "apex_to_www": True, "domain": "example.com"})["output"]
assert "RewriteCond %{HTTPS} off" in r and "RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]" in r
assert r.index("# Force HTTPS") < r.index("# Canonical: www domain")
assert g([{"from": "old", "to": "/new", "code": 301}])["error"] == 'Rule 1: "from" must be a path starting with / (no spaces)'
assert g([{"from": "/a", "to": " ", "code": 301}])["error"] == 'Rule 1: "to" is required'
assert g([{"from": "/a", "to": "/b", "code": 410}])["error"] == "Rule 1: code must be 301, 302 or 308"
assert g([{"from": "/a", "to": "/b", "code": 301}, {"from": "/a", "to": "/c", "code": 302}])["error"] == 'Duplicate "from" path: /a'
assert g([], {"www_to_apex": True, "apex_to_www": True, "domain": "e.com"})["error"] == "Pick one canonical direction: www→apex or apex→www"
assert g([], {"www_to_apex": True})["error"] == "A domain is required for www canonicalization"
assert g([], {"www_to_apex": True, "domain": "https://e.com"})["error"] == "Domain must be a bare host, without a protocol"
print("all showcase tests passed")
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →