Skip to content

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

// htaccess-generator — Apache .htaccess Redirect Generator. Zig 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 err. Never panics on plain input; errors travel
// in the result (err == null ⇔ TS error: null).
//
// Self-contained: Zig standard library only (std.mem/std.fmt scans replace
// the two TS regex literals; no external packages). Output and error strings
// are allocated from the caller's allocator and must be freed by the caller.
// Self-test: zig test zig.zig

const std = @import("std");

const HEADER = "# Generated by CosmoDev — .htaccess";

/// JS /\s/ on single bytes (ASCII whitespace).
const WS_CHARS = " \t\n\r\x0b\x0c";

pub const RedirectRule = struct {
    /// Must start with "/" and contain no whitespace.
    from: []const u8,
    /// Absolute URL or a root-relative path.
    to: []const u8,
    /// 301, 302 or 308 (anything else is rejected at runtime).
    code: i32,
};

pub const Options = struct {
    force_https: bool = false,
    /// www.example.com → example.com. Mutually exclusive with apex_to_www.
    www_to_apex: bool = false,
    /// example.com → www.example.com. Mutually exclusive with www_to_apex.
    apex_to_www: bool = false,
    /// Bare host, no protocol, no path. Required by either www rule.
    domain: []const u8 = "",
};

pub const HtaccessResult = struct {
    output: []const u8,
    /// null ⇔ TS error: null; non-null always comes with output == "".
    err: ?[]const u8,
};

fn hasWhitespace(s: []const u8) bool {
    for (s) |c| if (std.ascii.isWhitespace(c)) return true;
    return false;
}

/// /\./g → "\\.": backslash-escape every dot in the bare host.
fn escapeDots(alloc: std.mem.Allocator, domain: []const u8) ![]u8 {
    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(alloc);
    for (domain) |c| {
        if (c == '.') try out.append(alloc, '\\');
        try out.append(alloc, c);
    }
    return alloc.dupe(u8, out.items);
}

fn appendInt(list: *std.ArrayList(u8), alloc: std.mem.Allocator, v: i32) !void {
    var buf: [16]u8 = undefined; // 16 bytes always holds an i32 — infallible
    const s = std.fmt.bufPrint(&buf, "{d}", .{v}) catch unreachable;
    try list.appendSlice(alloc, s);
}

fn errf(alloc: std.mem.Allocator, comptime fmt: []const u8, args: anytype) HtaccessResult {
    return .{ .output = "", .err = std.fmt.allocPrint(alloc, fmt, args) catch "out of memory" };
}

/// Generate .htaccess content from rules and options. Twin of
/// generateHtaccess() in src/lib/htaccess-generator.ts.
pub fn generateHtaccess(
    alloc: std.mem.Allocator,
    rules: []const RedirectRule,
    opts: Options,
) std.mem.Allocator.Error!HtaccessResult {
    var seen = std.StringHashMap(void).init(alloc);
    defer seen.deinit();
    for (rules, 0..) |r, i| {
        if (!std.mem.startsWith(u8, r.from, "/") or hasWhitespace(r.from))
            return errf(alloc, "Rule {d}: \"from\" must be a path starting with / (no spaces)", .{i + 1});
        if (std.mem.trim(u8, r.to, WS_CHARS).len == 0)
            return errf(alloc, "Rule {d}: \"to\" is required", .{i + 1});
        if (r.code != 301 and r.code != 302 and r.code != 308)
            return errf(alloc, "Rule {d}: code must be 301, 302 or 308", .{i + 1});
        if (seen.contains(r.from))
            return errf(alloc, "Duplicate \"from\" path: {s}", .{r.from});
        try seen.put(r.from, {});
    }
    if (opts.www_to_apex and opts.apex_to_www)
        return .{ .output = "", .err = "Pick one canonical direction: www→apex or apex→www" };
    const wants_www = opts.www_to_apex or opts.apex_to_www;
    if (wants_www and opts.domain.len == 0)
        return .{ .output = "", .err = "A domain is required for www canonicalization" };
    if (opts.domain.len != 0 and
        (std.mem.startsWith(u8, opts.domain, "http://") or std.mem.startsWith(u8, opts.domain, "https://")))
        return .{ .output = "", .err = "Domain must be a bare host, without a protocol" };

    var body: std.ArrayList(u8) = .empty;
    defer body.deinit(alloc);
    var nsec: usize = 0; // max two sections: IfModule block + Redirects

    if (opts.force_https or wants_www) {
        if (nsec > 0) try body.appendSlice(alloc, "\n\n");
        nsec += 1;
        try body.appendSlice(alloc, "<IfModule mod_rewrite.c>\nRewriteEngine On");
        if (opts.force_https)
            try body.appendSlice(alloc, "\n\n# Force HTTPS\nRewriteCond %{HTTPS} off\n" ++
                "RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]");
        if (wants_www and opts.domain.len != 0) {
            const host = try escapeDots(alloc, opts.domain);
            defer alloc.free(host);
            try body.appendSlice(alloc, "\n\n# Canonical: ");
            try body.appendSlice(alloc, if (opts.www_to_apex) "apex domain" else "www domain");
            try body.appendSlice(alloc, "\n");
            if (opts.www_to_apex) {
                try body.appendSlice(alloc, "RewriteCond %{HTTP_HOST} ^www\\.");
                try body.appendSlice(alloc, host);
                try body.appendSlice(alloc, "$ [NC]\nRewriteRule ^ https://");
                try body.appendSlice(alloc, opts.domain);
                try body.appendSlice(alloc, "%{REQUEST_URI} [L,R=301]");
            } else {
                try body.appendSlice(alloc, "RewriteCond %{HTTP_HOST} ^");
                try body.appendSlice(alloc, host);
                try body.appendSlice(alloc, "$ [NC]\nRewriteRule ^ https://www.");
                try body.appendSlice(alloc, opts.domain);
                try body.appendSlice(alloc, "%{REQUEST_URI} [L,R=301]");
            }
        }
        try body.appendSlice(alloc, "\n</IfModule>");
    }
    if (rules.len > 0) {
        if (nsec > 0) try body.appendSlice(alloc, "\n\n");
        nsec += 1;
        try body.appendSlice(alloc, "# Redirects");
        for (rules) |r| {
            try body.appendSlice(alloc, "\nRedirect ");
            try appendInt(&body, alloc, r.code);
            try body.appendSlice(alloc, " ");
            try body.appendSlice(alloc, r.from);
            try body.appendSlice(alloc, " ");
            try body.appendSlice(alloc, r.to);
        }
    }
    if (nsec == 0) return .{ .output = "", .err = null }; // NOT an error

    const total = HEADER.len + 2 + body.items.len + 1;
    const out = try alloc.alloc(u8, total);
    @memcpy(out[0..HEADER.len], HEADER);
    out[HEADER.len] = '\n';
    out[HEADER.len + 1] = '\n';
    @memcpy(out[HEADER.len + 2 .. total - 1], body.items);
    out[total - 1] = '\n';
    return .{ .output = out, .err = null };
}

test "empty is empty, not an error" {
    const res = try generateHtaccess(std.testing.allocator, &.{}, .{});
    try std.testing.expectEqualStrings("", res.output);
    try std.testing.expect(res.err == null);
}

test "single redirect" {
    const rules = [_]RedirectRule{.{ .from = "/old", .to = "/new", .code = 301 }};
    const res = try generateHtaccess(std.testing.allocator, &rules, .{});
    defer std.testing.allocator.free(res.output);
    try std.testing.expectEqualStrings(
        "# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n",
        res.output,
    );
    try std.testing.expect(res.err == null);
}

test "force https then canonical, in that order" {
    const res = try generateHtaccess(std.testing.allocator, &.{}, .{
        .force_https = true,
        .apex_to_www = true,
        .domain = "example.com",
    });
    defer std.testing.allocator.free(res.output);
    try std.testing.expect(res.err == null);
    try std.testing.expect(std.mem.indexOf(u8, res.output, "RewriteCond %{HTTPS} off") != null);
    try std.testing.expect(std.mem.indexOf(u8, res.output, "RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]") != null);
    try std.testing.expect(std.mem.indexOf(u8, res.output, "RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]") != null);
    try std.testing.expect(std.mem.indexOf(u8, res.output, "# Force HTTPS").? <
        std.mem.indexOf(u8, res.output, "# Canonical: www domain").?);
}

test "validation errors match the TS strings" {
    const a = std.testing.allocator;
    const bad_from = [_]RedirectRule{.{ .from = "old", .to = "/new", .code = 301 }};
    var res = try generateHtaccess(a, &bad_from, .{});
    defer a.free(res.err.?);
    try std.testing.expectEqualStrings("Rule 1: \"from\" must be a path starting with / (no spaces)", res.err.?);

    const blank_to = [_]RedirectRule{.{ .from = "/a", .to = "  ", .code = 301 }};
    res = try generateHtaccess(a, &blank_to, .{});
    defer a.free(res.err.?);
    try std.testing.expectEqualStrings("Rule 1: \"to\" is required", res.err.?);

    const bad_code = [_]RedirectRule{.{ .from = "/a", .to = "/b", .code = 410 }};
    res = try generateHtaccess(a, &bad_code, .{});
    defer a.free(res.err.?);
    try std.testing.expectEqualStrings("Rule 1: code must be 301, 302 or 308", res.err.?);

    const dup = [_]RedirectRule{
        .{ .from = "/a", .to = "/b", .code = 301 },
        .{ .from = "/a", .to = "/c", .code = 302 },
    };
    res = try generateHtaccess(a, &dup, .{});
    defer a.free(res.err.?);
    try std.testing.expectEqualStrings("Duplicate \"from\" path: /a", res.err.?);

    res = try generateHtaccess(a, &.{}, .{ .www_to_apex = true, .apex_to_www = true, .domain = "e.com" });
    defer a.free(res.err.?);
    try std.testing.expectEqualStrings("Pick one canonical direction: www→apex or apex→www", res.err.?);

    res = try generateHtaccess(a, &.{}, .{ .www_to_apex = true });
    defer a.free(res.err.?);
    try std.testing.expectEqualStrings("A domain is required for www canonicalization", res.err.?);

    res = try generateHtaccess(a, &.{}, .{ .www_to_apex = true, .domain = "https://e.com" });
    defer a.free(res.err.?);
    try std.testing.expectEqualStrings("Domain must be a bare host, without a protocol", res.err.?);
}

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 →