Skip to content

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

// Pure surface of the .htaccess Redirect Generator (slug: htaccess-generator).
// Composes Apache directives from validated rules: per-rule Redirect lines
// (301/302/308) plus optional force-HTTPS and www canonicalization blocks.
// The validation rules and the exact section order (HTTPS, canonical, then
// redirects) are the contract a Go CLI twin must reproduce.
export interface RedirectRule {
  /** Source path, must start with "/" and contain no whitespace. */
  from: string;
  /** Target: absolute URL or a root-relative path. */
  to: string;
  code: 301 | 302 | 308;
}

export interface HtaccessOptions {
  forceHttps?: boolean;
  /** www.example.com → example.com. Mutually exclusive with apexToWww. */
  wwwToApex?: boolean;
  /** example.com → www.example.com. Mutually exclusive with wwwToApex. */
  apexToWww?: boolean;
  /** Bare host, no protocol, no path. Required by either www rule. */
  domain?: string;
}

export type HtaccessResult =
  | { output: string; error: null }
  /** No rules and no flags selected — nothing to generate, not an error. */
  | { output: ''; error: null }
  | { output: ''; error: string };

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

/** Generate .htaccess content from rules and options. */
export function generateHtaccess(rules: RedirectRule[], options: HtaccessOptions = {}): HtaccessResult {
  const seen = new Set<string>();
  for (const [i, r] of rules.entries()) {
    if (!r.from.startsWith('/') || /\s/.test(r.from)) {
      return { output: '', error: `Rule ${i + 1}: "from" must be a path starting with / (no spaces)` };
    }
    if (!r.to.trim()) return { output: '', error: `Rule ${i + 1}: "to" is required` };
    if (![301, 302, 308].includes(r.code)) {
      return { output: '', error: `Rule ${i + 1}: code must be 301, 302 or 308` };
    }
    if (seen.has(r.from)) return { output: '', error: `Duplicate "from" path: ${r.from}` };
    seen.add(r.from);
  }
  if (options.wwwToApex && options.apexToWww) {
    return { output: '', error: 'Pick one canonical direction: www→apex or apex→www' };
  }
  const wantsWww = options.wwwToApex || options.apexToWww;
  if (wantsWww && !options.domain) {
    return { output: '', error: 'A domain is required for www canonicalization' };
  }
  if (options.domain && /^https?:\/\//.test(options.domain)) {
    return { output: '', error: 'Domain must be a bare host, without a protocol' };
  }

  const sections: string[] = [];
  if (options.forceHttps || wantsWww) {
    const inner: string[] = ['RewriteEngine On'];
    if (options.forceHttps) {
      inner.push('', '# Force HTTPS', 'RewriteCond %{HTTPS} off', 'RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]');
    }
    if (wantsWww && options.domain) {
      const host = options.domain.replace(/\./g, '\\.');
      inner.push(
        '',
        `# Canonical: ${options.wwwToApex ? 'apex domain' : 'www domain'}`,
        ...(options.wwwToApex
          ? [`RewriteCond %{HTTP_HOST} ^www\\.${host}$ [NC]`, `RewriteRule ^ https://${options.domain}%{REQUEST_URI} [L,R=301]`]
          : [`RewriteCond %{HTTP_HOST} ^${host}$ [NC]`, `RewriteRule ^ https://www.${options.domain}%{REQUEST_URI} [L,R=301]`]),
      );
    }
    sections.push(`<IfModule mod_rewrite.c>\n${inner.join('\n')}\n</IfModule>`);
  }
  if (rules.length > 0) {
    sections.push(['# Redirects', ...rules.map((r) => `Redirect ${r.code} ${r.from} ${r.to}`)].join('\n'));
  }
  if (sections.length === 0) return { output: '', error: null };
  return { output: [HEADER, ...sections].join('\n\n') + '\n', error: null };
}

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 →