.htaccess Redirect Generator — Rust 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 Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! htaccess-generator — Apache .htaccess Redirect Generator. Rust 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. No rules and no flags is NOT an
//! error — empty output, `error: None`. Never panics on plain input; errors
//! travel in the result (`error: Some`).
//!
//! Self-contained: std only (no crates.io dependencies — no `regex`; the two
//! regex guards are expressed as `starts_with`/`is_whitespace` scans).
use std::collections::HashSet;
/// One redirect: `from` must start with "/" and contain no whitespace; `to`
/// is an absolute URL or a root-relative path; `code` is 301, 302 or 308
/// (anything else is rejected at runtime, mirroring the TS union guard).
pub struct RedirectRule {
pub from: String,
pub to: String,
pub code: i32,
}
/// Options; `Default` mirrors TS `generateHtaccess(rules, {})`.
#[derive(Default)]
pub struct HtaccessOptions {
pub force_https: bool,
/// www.example.com → example.com. Mutually exclusive with `apex_to_www`.
pub www_to_apex: bool,
/// example.com → www.example.com. Mutually exclusive with `www_to_apex`.
pub apex_to_www: bool,
/// Bare host, no protocol, no path. Required by either www rule.
pub domain: String,
}
/// TS `HtaccessResult` union: `error: None` ⇔ TS `error: null`;
/// `error: Some(_)` always comes with an empty `output`.
pub struct HtaccessResult {
pub output: String,
pub error: Option<String>,
}
fn fail(message: String) -> HtaccessResult {
HtaccessResult { output: String::new(), error: Some(message) }
}
/// Generate .htaccess content from rules and options. Twin of
/// `generateHtaccess` in src/lib/htaccess-generator.ts.
pub fn generate_htaccess(rules: &[RedirectRule], o: &HtaccessOptions) -> HtaccessResult {
const HEADER: &str = "# Generated by CosmoDev — .htaccess";
let mut seen: HashSet<&str> = HashSet::new();
for (i, r) in rules.iter().enumerate() {
if !r.from.starts_with('/') || r.from.chars().any(char::is_whitespace) {
return fail(format!("Rule {}: \"from\" must be a path starting with / (no spaces)", i + 1));
}
if r.to.trim().is_empty() {
return fail(format!("Rule {}: \"to\" is required", i + 1));
}
if !matches!(r.code, 301 | 302 | 308) {
return fail(format!("Rule {}: code must be 301, 302 or 308", i + 1));
}
if !seen.insert(r.from.as_str()) {
return fail(format!("Duplicate \"from\" path: {}", r.from));
}
}
if o.www_to_apex && o.apex_to_www {
return fail("Pick one canonical direction: www→apex or apex→www".into());
}
let wants_www = o.www_to_apex || o.apex_to_www;
if wants_www && o.domain.is_empty() {
return fail("A domain is required for www canonicalization".into());
}
// TS guard /^https?:\/\// on the bare-host domain.
if !o.domain.is_empty() && (o.domain.starts_with("http://") || o.domain.starts_with("https://")) {
return fail("Domain must be a bare host, without a protocol".into());
}
let mut sections: Vec<String> = Vec::new();
if o.force_https || wants_www {
let mut inner: Vec<String> = vec!["RewriteEngine On".to_string()];
if o.force_https {
inner.extend(
["", "# Force HTTPS", "RewriteCond %{HTTPS} off",
"RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]"]
.iter()
.map(|s| s.to_string()),
);
}
if wants_www && !o.domain.is_empty() {
let host = o.domain.replace('.', "\\."); // /\./g → '\.'
inner.push(String::new());
inner.push(if o.www_to_apex { "# Canonical: apex domain" } else { "# Canonical: www domain" }.to_string());
if o.www_to_apex {
inner.push(format!("RewriteCond %{{HTTP_HOST}} ^www\\.{host}$ [NC]"));
inner.push(format!("RewriteRule ^ https://{}%{{REQUEST_URI}} [L,R=301]", o.domain));
} else {
inner.push(format!("RewriteCond %{{HTTP_HOST}} ^{host}$ [NC]"));
inner.push(format!("RewriteRule ^ https://www.{}%{{REQUEST_URI}} [L,R=301]", o.domain));
}
}
sections.push(format!("<IfModule mod_rewrite.c>\n{}\n</IfModule>", inner.join("\n")));
}
if !rules.is_empty() {
let mut lines: Vec<String> = vec!["# Redirects".to_string()];
lines.extend(rules.iter().map(|r| format!("Redirect {} {} {}", r.code, r.from, r.to)));
sections.push(lines.join("\n"));
}
if sections.is_empty() {
// Nothing to generate — empty output is NOT an error (TS: error: null).
return HtaccessResult { output: String::new(), error: None };
}
let mut parts: Vec<String> = vec![HEADER.to_string()];
parts.extend(sections);
HtaccessResult { output: parts.join("\n\n") + "\n", error: None }
}
#[cfg(test)]
mod tests {
use super::*;
fn rule(from: &str, to: &str, code: i32) -> RedirectRule {
RedirectRule { from: from.to_string(), to: to.to_string(), code }
}
#[test]
fn empty_is_empty_not_error() {
let r = generate_htaccess(&[], &HtaccessOptions::default());
assert_eq!(r.output, "");
assert_eq!(r.error, None);
}
#[test]
fn single_redirect() {
let rules = vec![rule("/old", "/new", 301)];
let r = generate_htaccess(&rules, &HtaccessOptions::default());
assert_eq!(r.error, None);
assert_eq!(
r.output,
"# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n"
);
}
#[test]
fn force_https_then_canonical_section_order() {
let opts = HtaccessOptions { force_https: true, apex_to_www: true, domain: "example.com".into(), ..Default::default() };
let r = generate_htaccess(&[], &opts);
assert_eq!(r.error, None);
assert!(r.output.contains("RewriteCond %{HTTPS} off"));
assert!(r.output.contains("RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]"));
assert!(r.output.contains("RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]"));
assert!(r.output.find("# Force HTTPS").unwrap() < r.output.find("# Canonical: www domain").unwrap());
}
#[test]
fn validation_errors_match_ts() {
let o = HtaccessOptions::default();
let g = |rules: &[RedirectRule]| generate_htaccess(rules, &o).error.unwrap();
assert_eq!(g(&[rule("old", "/new", 301)]), "Rule 1: \"from\" must be a path starting with / (no spaces)");
assert_eq!(g(&[rule("/a", " ", 301)]), "Rule 1: \"to\" is required");
assert_eq!(g(&[rule("/a", "/b", 410)]), "Rule 1: code must be 301, 302 or 308");
assert_eq!(g(&[rule("/a", "/b", 301), rule("/a", "/c", 302)]), "Duplicate \"from\" path: /a");
let both = HtaccessOptions { www_to_apex: true, apex_to_www: true, domain: "e.com".into(), ..Default::default() };
assert_eq!(generate_htaccess(&[], &both).error.unwrap(), "Pick one canonical direction: www→apex or apex→www");
let no_domain = HtaccessOptions { www_to_apex: true, ..Default::default() };
assert_eq!(generate_htaccess(&[], &no_domain).error.unwrap(), "A domain is required for www canonicalization");
let proto = HtaccessOptions { www_to_apex: true, domain: "https://e.com".into(), ..Default::default() };
assert_eq!(generate_htaccess(&[], &proto).error.unwrap(), "Domain must be a bare host, without a protocol");
}
}
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 →