Skip to content

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

// Package htaccessgenerator is the Go twin of CosmoDev's
// src/lib/htaccess-generator.ts (dual source: the web lib is TypeScript, the
// CLI lib is Go — kept in lock-step). Pure + deterministic, never panics. The
// table-driven tests in htaccess-generator_test.go share vectors with
// src/lib/htaccess-generator.test.ts so the two implementations are held to
// the same contract.
//
// Behaviour mirrors the TS lib exactly: validate every rule in order (from
// path, to target, status code, duplicate from-paths), then the
// www-canonicalization options (mutual exclusion, required bare domain, no
// protocol), then compose sections in fixed order — the IfModule mod_rewrite.c
// block (RewriteEngine On + optional Force HTTPS + optional www
// canonicalization, dots escaped in the host condition) first, then the
// Redirect lines — joined by a single blank line under the header comment.
// No rules and no flags produce an empty output, not an error.
package htaccessgenerator

import (
	"fmt"
	"regexp"
	"slices"
	"strings"
)

// RedirectRule mirrors src/lib/htaccess-generator.ts RedirectRule. Code is a
// plain int rather than a named type so invalid codes (e.g. 410) can be
// expressed and rejected at runtime — exactly what the TS validator guards
// against behind its 301|302|308 union type.
type RedirectRule struct {
	From string // source path: must start with "/" and contain no whitespace
	To   string // target: absolute URL or a root-relative path
	Code int    // 301, 302 or 308
}

// Options mirrors src/lib/htaccess-generator.ts HtaccessOptions. The zero
// value (Options{}) matches the TS default (generateHtaccess(rules, {})):
// no force-HTTPS, no www canonicalization, no domain.
type Options struct {
	ForceHTTPS bool
	// WWWToApex rewrites www.<domain> → <domain>. Mutually exclusive with
	// ApexToWWW.
	WWWToApex bool
	// ApexToWWW rewrites <domain> → www.<domain>. Mutually exclusive with
	// WWWToApex.
	ApexToWWW bool
	// Domain is the bare host (no protocol, no path). Required by either
	// www rule.
	Domain string
}

// Result mirrors the TS HtaccessResult union: either the generated output with
// no error, or an empty output with a validation error message. Error == ""
// corresponds to the TS `error: null` case; a non-empty Error always comes
// with an empty Output, exactly like the TS union.
type Result struct {
	Output string
	Error  string
}

// header is the first line of every non-empty generation. Same text as HEADER
// in the TS lib (note the em dash).
const header = "# Generated by CosmoDev — .htaccess"

var (
	// whitespace matches any whitespace character, mirroring /\s/ in the TS
	// "from" guard.
	whitespace = regexp.MustCompile(`\s`)
	// protoDomain matches a domain that carries an http(s) protocol,
	// mirroring /^https?:\/\// in the TS domain guard.
	protoDomain = regexp.MustCompile(`^https?://`)
)

// redirectCodes lists the accepted Redirect status codes, mirroring the TS
// [301, 302, 308].includes(code) guard.
var redirectCodes = []int{301, 302, 308}

// GenerateHtaccess generates .htaccess content from rules and options. It is
// the Go twin of generateHtaccess() in src/lib/htaccess-generator.ts and must
// agree with it on every shared vector.
func GenerateHtaccess(rules []RedirectRule, opts Options) Result {
	seen := make(map[string]bool, len(rules))
	for i, r := range rules {
		if !strings.HasPrefix(r.From, "/") || whitespace.MatchString(r.From) {
			return Result{Error: fmt.Sprintf("Rule %d: \"from\" must be a path starting with / (no spaces)", i+1)}
		}
		if strings.TrimSpace(r.To) == "" {
			return Result{Error: fmt.Sprintf("Rule %d: \"to\" is required", i+1)}
		}
		if !slices.Contains(redirectCodes, r.Code) {
			return Result{Error: fmt.Sprintf("Rule %d: code must be 301, 302 or 308", i+1)}
		}
		if seen[r.From] {
			return Result{Error: fmt.Sprintf("Duplicate \"from\" path: %s", r.From)}
		}
		seen[r.From] = true
	}
	if opts.WWWToApex && opts.ApexToWWW {
		return Result{Error: "Pick one canonical direction: www→apex or apex→www"}
	}
	wantsWww := opts.WWWToApex || opts.ApexToWWW
	if wantsWww && opts.Domain == "" {
		return Result{Error: "A domain is required for www canonicalization"}
	}
	if opts.Domain != "" && protoDomain.MatchString(opts.Domain) {
		return Result{Error: "Domain must be a bare host, without a protocol"}
	}

	var sections []string
	if opts.ForceHTTPS || wantsWww {
		inner := []string{"RewriteEngine On"}
		if opts.ForceHTTPS {
			inner = append(inner,
				"",
				"# Force HTTPS",
				"RewriteCond %{HTTPS} off",
				`RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]`,
			)
		}
		if wantsWww && opts.Domain != "" {
			// Escape dots in the host regex, mirroring /\./g → '\\.'.
			host := strings.ReplaceAll(opts.Domain, ".", `\.`)
			// Same ternary as the TS lib: wwwToApex → 'apex domain'.
			label := "www domain"
			if opts.WWWToApex {
				label = "apex domain"
			}
			inner = append(inner, "", "# Canonical: "+label)
			if opts.WWWToApex {
				inner = append(inner,
					`RewriteCond %{HTTP_HOST} ^www\.`+host+`$ [NC]`,
					`RewriteRule ^ https://`+opts.Domain+`%{REQUEST_URI} [L,R=301]`,
				)
			} else {
				inner = append(inner,
					`RewriteCond %{HTTP_HOST} ^`+host+`$ [NC]`,
					`RewriteRule ^ https://www.`+opts.Domain+`%{REQUEST_URI} [L,R=301]`,
				)
			}
		}
		sections = append(sections, "<IfModule mod_rewrite.c>\n"+strings.Join(inner, "\n")+"\n</IfModule>")
	}
	if len(rules) > 0 {
		lines := make([]string, 0, len(rules)+1)
		lines = append(lines, "# Redirects")
		for _, r := range rules {
			lines = append(lines, fmt.Sprintf("Redirect %d %s %s", r.Code, r.From, r.To))
		}
		sections = append(sections, strings.Join(lines, "\n"))
	}
	if len(sections) == 0 {
		// Nothing to generate — empty output is NOT an error (TS: error: null).
		return Result{}
	}
	// Sections joined by a single blank line, header comment first, trailing
	// newline — exactly [HEADER, ...sections].join('\n\n') + '\n'.
	return Result{Output: header + "\n\n" + strings.Join(sections, "\n\n") + "\n"}
}

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 →