.htaccess Redirect Generator — JavaScript 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 JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* htaccess-generator — Apache .htaccess Redirect Generator. JavaScript 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 — { output: '', error: null }. Never throws on plain-object input.
*
* Self-contained: stdlib only (no npm dependencies); ESM export (this repo is
* package.json "type": "module") consumable from Node 16+ without a build
* step. Direct execution runs the showcase tests (import.meta.main, Node
* 20.11+ / Deno / Bun).
*/
'use strict';
const HEADER = '# Generated by CosmoDev — .htaccess';
/**
* @param {Array<{from: string, to: string, code: number}>} rules
* @param {{forceHttps?: boolean, wwwToApex?: boolean, apexToWww?: boolean, domain?: string}} [options]
* @returns {{output: string, error: string | null}}
*/
function generateHtaccess(rules, options = {}) {
const seen = new Set();
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 = [];
if (options.forceHttps || wantsWww) {
const inner = ['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'}`);
if (options.wwwToApex) {
inner.push(`RewriteCond %{HTTP_HOST} ^www\\.${host}$ [NC]`, `RewriteRule ^ https://${options.domain}%{REQUEST_URI} [L,R=301]`);
} else {
inner.push(`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 };
}
export { generateHtaccess };
// Example:
// generateHtaccess([{ from: '/old', to: '/new', code: 301 }]).output
// → '# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n'
if (import.meta.main) {
const assert = (await import('node:assert')).strict;
const g = generateHtaccess;
assert.deepStrictEqual(g([]), { output: '', error: null });
assert.strictEqual(
g([{ from: '/old', to: '/new', code: 301 }]).output,
'# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n',
);
const r = g([], { forceHttps: true, apexToWww: true, domain: 'example.com' });
assert.strictEqual(r.error, null);
assert.ok(r.output.includes('RewriteCond %{HTTPS} off'));
assert.ok(r.output.includes('RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]'));
assert.ok(r.output.indexOf('# Force HTTPS') < r.output.indexOf('# Canonical: www domain'));
assert.strictEqual(g([{ from: 'old', to: '/new', code: 301 }]).error,
'Rule 1: "from" must be a path starting with / (no spaces)');
assert.strictEqual(g([{ from: '/a', to: ' ', code: 301 }]).error, 'Rule 1: "to" is required');
assert.strictEqual(g([{ from: '/a', to: '/b', code: 410 }]).error, 'Rule 1: code must be 301, 302 or 308');
assert.strictEqual(
g([{ from: '/a', to: '/b', code: 301 }, { from: '/a', to: '/c', code: 302 }]).error,
'Duplicate "from" path: /a');
assert.strictEqual(g([], { wwwToApex: true, apexToWww: true, domain: 'e.com' }).error,
'Pick one canonical direction: www→apex or apex→www');
assert.strictEqual(g([], { wwwToApex: true }).error, 'A domain is required for www canonicalization');
assert.strictEqual(g([], { wwwToApex: true, domain: 'https://e.com' }).error,
'Domain must be a bare host, without a protocol');
console.log('all showcase tests passed');
}
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 →