Skip to content

.htaccess Redirect Generator — Swift 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 Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.

// htaccess-generator — Apache .htaccess Redirect Generator. Swift 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, nil error. Never traps on plain input; errors
// travel in the result.
//
// Self-contained: Foundation only (no SPM dependencies). Script-mode demo:
// swift swift.swift

import Foundation

struct RedirectRule {
    let from: String  // must start with "/" and contain no whitespace
    let to: String    // absolute URL or a root-relative path
    let code: Int     // 301, 302 or 308 (anything else is rejected at runtime)
}

struct HtaccessOptions {
    var forceHttps = false
    var wwwToApex = false // www.example.com → example.com
    var apexToWww = false // example.com → www.example.com
    var domain = ""       // bare host, required by either www rule
}

/// TS HtaccessResult union: error == nil ⇔ error: null.
struct HtaccessResult {
    let output: String
    let error: String?
}

private let header = "# Generated by CosmoDev — .htaccess"

/// Generate .htaccess content from rules and options. Twin of
/// generateHtaccess() in src/lib/htaccess-generator.ts.
func generateHtaccess(_ rules: [RedirectRule], _ options: HtaccessOptions = HtaccessOptions()) -> HtaccessResult {
    var seen = Set<String>()
    for (i, r) in rules.enumerated() {
        if !r.from.hasPrefix("/") || r.from.rangeOfCharacter(from: .whitespacesAndNewlines) != nil {
            return HtaccessResult(output: "", error: "Rule \(i + 1): \"from\" must be a path starting with / (no spaces)")
        }
        if r.to.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
            return HtaccessResult(output: "", error: "Rule \(i + 1): \"to\" is required")
        }
        if ![301, 302, 308].contains(r.code) {
            return HtaccessResult(output: "", error: "Rule \(i + 1): code must be 301, 302 or 308")
        }
        if seen.contains(r.from) {
            return HtaccessResult(output: "", error: "Duplicate \"from\" path: \(r.from)")
        }
        seen.insert(r.from)
    }
    if options.wwwToApex && options.apexToWww {
        return HtaccessResult(output: "", error: "Pick one canonical direction: www→apex or apex→www")
    }
    let wantsWww = options.wwwToApex || options.apexToWww
    if wantsWww && options.domain.isEmpty {
        return HtaccessResult(output: "", error: "A domain is required for www canonicalization")
    }
    if !options.domain.isEmpty && (options.domain.hasPrefix("http://") || options.domain.hasPrefix("https://")) {
        return HtaccessResult(output: "", error: "Domain must be a bare host, without a protocol")
    }

    var sections: [String] = []
    if options.forceHttps || wantsWww {
        var inner = ["RewriteEngine On"]
        if options.forceHttps {
            inner += ["", "# Force HTTPS", "RewriteCond %{HTTPS} off",
                      "RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]"]
        }
        if wantsWww && !options.domain.isEmpty {
            let host = options.domain.replacingOccurrences(of: ".", with: "\\.") // /\./g → "\\."
            inner += ["", "# Canonical: \(options.wwwToApex ? "apex domain" : "www domain")"]
            if options.wwwToApex {
                inner += ["RewriteCond %{HTTP_HOST} ^www\\.\(host)$ [NC]",
                          "RewriteRule ^ https://\(options.domain)%{REQUEST_URI} [L,R=301]"]
            } else {
                inner += ["RewriteCond %{HTTP_HOST} ^\(host)$ [NC]",
                          "RewriteRule ^ https://www.\(options.domain)%{REQUEST_URI} [L,R=301]"]
            }
        }
        sections.append("<IfModule mod_rewrite.c>\n\(inner.joined(separator: "\n"))\n</IfModule>")
    }
    if !rules.isEmpty {
        sections.append((["# Redirects"] + rules.map { "Redirect \($0.code) \($0.from) \($0.to)" })
            .joined(separator: "\n"))
    }
    if sections.isEmpty {
        return HtaccessResult(output: "", error: nil) // nothing to generate — NOT an error
    }
    return HtaccessResult(output: ([header] + sections).joined(separator: "\n\n") + "\n", error: nil)
}

// Showcase tests (run: swift swift.swift)
assert(generateHtaccess([]).output.isEmpty && generateHtaccess([]).error == nil, "empty")
let single = generateHtaccess([RedirectRule(from: "/old", to: "/new", code: 301)])
assert(single.output == "# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n", "redirect")
let flags = generateHtaccess([], HtaccessOptions(forceHttps: true, wwwToApex: false, apexToWww: true, domain: "example.com"))
assert(flags.error == nil, "flags")
assert(flags.output.contains("RewriteCond %{HTTPS} off"), "force https")
assert(flags.output.contains("RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]"), "dot escape")
assert(flags.output.contains("RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]"), "www rule")
assert(flags.output.range(of: "# Force HTTPS")!.lowerBound < flags.output.range(of: "# Canonical: www domain")!.lowerBound, "section order")
assert(generateHtaccess([RedirectRule(from: "old", to: "/new", code: 301)]).error ==
    "Rule 1: \"from\" must be a path starting with / (no spaces)", "from")
assert(generateHtaccess([RedirectRule(from: "/a", to: "  ", code: 301)]).error == "Rule 1: \"to\" is required", "to")
assert(generateHtaccess([RedirectRule(from: "/a", to: "/b", code: 410)]).error == "Rule 1: code must be 301, 302 or 308", "code")
assert(generateHtaccess([RedirectRule(from: "/a", to: "/b", code: 301), RedirectRule(from: "/a", to: "/c", code: 302)]).error ==
    "Duplicate \"from\" path: /a", "duplicate")
assert(generateHtaccess([], HtaccessOptions(wwwToApex: true, apexToWww: true, domain: "e.com")).error ==
    "Pick one canonical direction: www→apex or apex→www", "direction")
assert(generateHtaccess([], HtaccessOptions(wwwToApex: true)).error ==
    "A domain is required for www canonicalization", "no domain")
assert(generateHtaccess([], HtaccessOptions(wwwToApex: true, domain: "https://e.com")).error ==
    "Domain must be a bare host, without a protocol", "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 →