.htaccess Redirect Generator — Kotlin 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 Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.
// htaccess-generator — Apache .htaccess Redirect Generator. Kotlin 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, null error. Never throws on plain input; errors
// travel in the result.
//
// Self-contained: Kotlin stdlib only (no external dependencies).
data class RedirectRule(val from: String, val to: String, val code: Int)
data class HtaccessOptions(
val forceHttps: Boolean = false,
val wwwToApex: Boolean = false, // www.example.com → example.com
val apexToWww: Boolean = false, // example.com → www.example.com
val domain: String = "", // bare host, required by either www rule
)
/** TS HtaccessResult union: error == null ⇔ error: null. */
data class HtaccessResult(val output: String, val error: String? = null)
private const val HEADER = "# Generated by CosmoDev — .htaccess"
private val WS = Regex("""\s""")
private val PROTOCOL = Regex("""^https?://""")
private val CODES = setOf(301, 302, 308)
/** Generate .htaccess content from rules and options. Twin of
* generateHtaccess() in src/lib/htaccess-generator.ts. */
fun generateHtaccess(
rules: List<RedirectRule>,
options: HtaccessOptions = HtaccessOptions(),
): HtaccessResult {
val seen = mutableSetOf<String>()
rules.forEachIndexed { i, r ->
if (!r.from.startsWith("/") || WS.containsMatchIn(r.from)) {
return HtaccessResult("", "Rule ${i + 1}: \"from\" must be a path starting with / (no spaces)")
}
if (r.to.trim().isEmpty()) {
return HtaccessResult("", "Rule ${i + 1}: \"to\" is required")
}
if (r.code !in CODES) {
return HtaccessResult("", "Rule ${i + 1}: code must be 301, 302 or 308")
}
if (!seen.add(r.from)) {
return HtaccessResult("", "Duplicate \"from\" path: ${r.from}")
}
}
if (options.wwwToApex && options.apexToWww) {
return HtaccessResult("", "Pick one canonical direction: www→apex or apex→www")
}
val wantsWww = options.wwwToApex || options.apexToWww
if (wantsWww && options.domain.isEmpty()) {
return HtaccessResult("", "A domain is required for www canonicalization")
}
if (options.domain.isNotEmpty() && PROTOCOL.containsMatchIn(options.domain)) {
return HtaccessResult("", "Domain must be a bare host, without a protocol")
}
val sections = mutableListOf<String>()
if (options.forceHttps || wantsWww) {
val inner = mutableListOf("RewriteEngine On")
if (options.forceHttps) {
inner += listOf("", "# Force HTTPS", "RewriteCond %{HTTPS} off",
"RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]")
}
if (wantsWww && options.domain.isNotEmpty()) {
val host = options.domain.replace(".", "\\.") // /\./g → "\\."
inner += ""
inner += "# Canonical: " + if (options.wwwToApex) "apex domain" else "www domain"
if (options.wwwToApex) {
inner += "RewriteCond %{HTTP_HOST} ^www\\.$host\$ [NC]"
inner += "RewriteRule ^ https://${options.domain}%{REQUEST_URI} [L,R=301]"
} else {
inner += "RewriteCond %{HTTP_HOST} ^$host\$ [NC]"
inner += "RewriteRule ^ https://www.${options.domain}%{REQUEST_URI} [L,R=301]"
}
}
sections += "<IfModule mod_rewrite.c>\n" + inner.joinToString("\n") + "\n</IfModule>"
}
if (rules.isNotEmpty()) {
sections += (listOf("# Redirects") + rules.map { "Redirect ${it.code} ${it.from} ${it.to}" })
.joinToString("\n")
}
if (sections.isEmpty()) {
return HtaccessResult("", null) // nothing to generate — NOT an error
}
return HtaccessResult((listOf(HEADER) + sections).joinToString("\n\n") + "\n", null)
}
/** Showcase tests: kotlinc kotlin.kt -include-runtime -d ht.jar && java -jar ht.jar */
fun main() {
check(generateHtaccess(emptyList()).output.isEmpty(), "empty")
check(
generateHtaccess(listOf(RedirectRule("/old", "/new", 301))).output ==
"# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n",
"redirect",
)
val w = HtaccessOptions(forceHttps = true, apexToWww = true, domain = "example.com")
val c = generateHtaccess(emptyList(), w)
check(c.error == null && c.output.contains("RewriteCond %{HTTPS} off"), "force https")
check(c.output.contains("RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]"), "dot escape")
check(c.output.indexOf("# Force HTTPS") < c.output.indexOf("# Canonical: www domain"), "section order")
check(
generateHtaccess(listOf(RedirectRule("old", "/new", 301))).error ==
"Rule 1: \"from\" must be a path starting with / (no spaces)",
"from",
)
check(generateHtaccess(listOf(RedirectRule("/a", " ", 301))).error == "Rule 1: \"to\" is required", "to")
check(generateHtaccess(listOf(RedirectRule("/a", "/b", 410))).error == "Rule 1: code must be 301, 302 or 308", "code")
check(
generateHtaccess(listOf(RedirectRule("/a", "/b", 301), RedirectRule("/a", "/c", 302))).error ==
"Duplicate \"from\" path: /a",
"duplicate",
)
check(
generateHtaccess(emptyList(), HtaccessOptions(wwwToApex = true, apexToWww = true, domain = "e.com")).error ==
"Pick one canonical direction: www→apex or apex→www",
"direction",
)
check(
generateHtaccess(emptyList(), HtaccessOptions(wwwToApex = true)).error ==
"A domain is required for www canonicalization",
"no domain",
)
check(
generateHtaccess(emptyList(), HtaccessOptions(wwwToApex = true, domain = "https://e.com")).error ==
"Domain must be a bare host, without a protocol",
"protocol",
)
println("all showcase tests passed")
}
private fun check(ok: Boolean, label: String) {
if (!ok) throw IllegalStateException("FAILED: $label")
}
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 →