Skip to content

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

// htaccess-generator — Apache .htaccess Redirect Generator. C# 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 record.
//
// Self-contained: .NET base class library only (no NuGet dependencies).

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace CosmoDev.HtaccessGenerator
{
    /// <summary>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 301|302|308 union guard).</summary>
    public sealed record RedirectRule(string From, string To, int Code);

    /// <summary>Options; the parameterless constructor mirrors the TS default
    /// generateHtaccess(rules, {}).</summary>
    public sealed record HtaccessOptions(
        bool ForceHttps = false,
        bool WwwToApex = false,
        bool ApexToWww = false,
        string? Domain = null);

    /// <summary>TS HtaccessResult union: Error == null ⇔ error: null;
    /// non-null Error always comes with an empty Output.</summary>
    public sealed record HtaccessResult(string Output, string? Error);

    public static class HtaccessGenerator
    {
        private const string Header = "# Generated by CosmoDev — .htaccess";

        private static readonly Regex Whitespace = new(@"\s", RegexOptions.Compiled);
        private static readonly Regex Protocol = new(@"^https?://", RegexOptions.Compiled);
        private static readonly HashSet<int> RedirectCodes = new() { 301, 302, 308 };

        /// <summary>Generate .htaccess content from rules and options. Twin
        /// of generateHtaccess() in src/lib/htaccess-generator.ts.</summary>
        public static HtaccessResult Generate(RedirectRule[] rules, HtaccessOptions? options = null)
        {
            options ??= new HtaccessOptions();
            var seen = new HashSet<string>();
            for (var i = 0; i < rules.Length; i++)
            {
                var r = rules[i];
                if (!r.From.StartsWith("/") || Whitespace.IsMatch(r.From))
                    return new("", $"Rule {i + 1}: \"from\" must be a path starting with / (no spaces)");
                if (string.IsNullOrWhiteSpace(r.To))
                    return new("", $"Rule {i + 1}: \"to\" is required");
                if (!RedirectCodes.Contains(r.Code))
                    return new("", $"Rule {i + 1}: code must be 301, 302 or 308");
                if (!seen.Add(r.From))
                    return new("", $"Duplicate \"from\" path: {r.From}");
            }
            if (options.WwwToApex && options.ApexToWww)
                return new("", "Pick one canonical direction: www→apex or apex→www");
            var wantsWww = options.WwwToApex || options.ApexToWww;
            var domain = options.Domain ?? "";
            if (wantsWww && domain.Length == 0)
                return new("", "A domain is required for www canonicalization");
            if (domain.Length > 0 && Protocol.IsMatch(domain))
                return new("", "Domain must be a bare host, without a protocol");

            var sections = new List<string>();
            if (options.ForceHttps || wantsWww)
            {
                var inner = new List<string> { "RewriteEngine On" };
                if (options.ForceHttps)
                {
                    inner.AddRange(new[] { "", "# Force HTTPS", "RewriteCond %{HTTPS} off",
                        "RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]" });
                }
                if (wantsWww && domain.Length > 0)
                {
                    var host = domain.Replace(".", "\\."); // /\./g → "\\."
                    inner.Add("");
                    inner.Add($"# Canonical: {(options.WwwToApex ? "apex domain" : "www domain")}");
                    if (options.WwwToApex)
                    {
                        inner.Add($"RewriteCond %{{HTTP_HOST}} ^www\\.{host}$ [NC]");
                        inner.Add($"RewriteRule ^ https://{domain}%{{REQUEST_URI}} [L,R=301]");
                    }
                    else
                    {
                        inner.Add($"RewriteCond %{{HTTP_HOST}} ^{host}$ [NC]");
                        inner.Add($"RewriteRule ^ https://www.{domain}%{{REQUEST_URI}} [L,R=301]");
                    }
                }
                sections.Add($"<IfModule mod_rewrite.c>\n{string.Join("\n", inner)}\n</IfModule>");
            }
            if (rules.Length > 0)
            {
                var lines = new List<string> { "# Redirects" };
                foreach (var r in rules) lines.Add($"Redirect {r.Code} {r.From} {r.To}");
                sections.Add(string.Join("\n", lines));
            }
            if (sections.Count == 0)
                return new("", null); // nothing to generate — NOT an error
            var parts = new List<string> { Header };
            parts.AddRange(sections);
            return new(string.Join("\n\n", parts) + "\n", null);
        }

#if HTACCESS_SELFTEST
        public static void Main()
        {
            var r1 = Generate(Array.Empty<RedirectRule>());
            Console.WriteLine(r1.Output.Length == 0 && r1.Error == null ? "empty ok" : "EMPTY FAIL");
            var r2 = Generate(new[] { new RedirectRule("/old", "/new", 301) });
            Console.WriteLine(r2.Output == "# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n" ? "redirect ok" : "REDIRECT FAIL");
            var r3 = Generate(Array.Empty<RedirectRule>(), new HtaccessOptions(ForceHttps: true, ApexToWww: true, Domain: "example.com"));
            Console.WriteLine(r3.Error == null && r3.Output.Contains("RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]") ? "canonical ok" : "CANONICAL FAIL");
            var r4 = Generate(new[] { new RedirectRule("old", "/new", 301) });
            Console.WriteLine(r4.Error == "Rule 1: \"from\" must be a path starting with / (no spaces)" ? "from ok" : "FROM FAIL");
        }
#endif
    }
}

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 →