Skip to content

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

<?php
declare(strict_types=1);

/*
 * htaccess-generator — Apache .htaccess Redirect Generator. PHP 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: missing keys read as '',
 * errors travel in the result array.
 *
 * Self-contained: standard library only (no composer dependencies).
 */

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

/**
 * Build .htaccess text from rules and options.
 *
 * @param list<array{from?:string,to?:string,code?:int}> $rules
 * @param array{force_https?:bool,www_to_apex?:bool,apex_to_www?:bool,domain?:string} $options
 * @return array{output:string,error:?string} error null ⇔ TS error: null
 */
function generate_htaccess(array $rules, array $options = []): array
{
    $seen = [];
    foreach ($rules as $i => $r) {
        $from = (string) ($r['from'] ?? '');
        $to = (string) ($r['to'] ?? '');
        $code = $r['code'] ?? null;
        if (!str_starts_with($from, '/') || preg_match('/\s/', $from) === 1) {
            return ['output' => '', 'error' => sprintf('Rule %d: "from" must be a path starting with / (no spaces)', $i + 1)];
        }
        if (trim($to) === '') {
            return ['output' => '', 'error' => sprintf('Rule %d: "to" is required', $i + 1)];
        }
        if (!in_array($code, [301, 302, 308], true)) {
            return ['output' => '', 'error' => sprintf('Rule %d: code must be 301, 302 or 308', $i + 1)];
        }
        if (in_array($from, $seen, true)) {
            return ['output' => '', 'error' => sprintf('Duplicate "from" path: %s', $from)];
        }
        $seen[] = $from;
    }

    $forceHttps = (bool) ($options['force_https'] ?? false);
    $wwwToApex = (bool) ($options['www_to_apex'] ?? false);
    $apexToWww = (bool) ($options['apex_to_www'] ?? false);
    $domain = (string) ($options['domain'] ?? '');
    if ($wwwToApex && $apexToWww) {
        return ['output' => '', 'error' => 'Pick one canonical direction: www→apex or apex→www'];
    }
    $wantsWww = $wwwToApex || $apexToWww;
    if ($wantsWww && $domain === '') {
        return ['output' => '', 'error' => 'A domain is required for www canonicalization'];
    }
    if ($domain !== '' && preg_match('#^https?://#', $domain) === 1) {
        return ['output' => '', 'error' => 'Domain must be a bare host, without a protocol'];
    }

    $sections = [];
    if ($forceHttps || $wantsWww) {
        $inner = ['RewriteEngine On'];
        if ($forceHttps) {
            array_push($inner, '', '# Force HTTPS', 'RewriteCond %{HTTPS} off',
                'RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]');
        }
        if ($wantsWww && $domain !== '') {
            $host = str_replace('.', '\\.', $domain); // /\./g → '\\.'
            $inner[] = '';
            $inner[] = '# Canonical: ' . ($wwwToApex ? 'apex domain' : 'www domain');
            if ($wwwToApex) {
                $inner[] = "RewriteCond %{HTTP_HOST} ^www\\.{$host}\$ [NC]";
                $inner[] = "RewriteRule ^ https://{$domain}%{REQUEST_URI} [L,R=301]";
            } else {
                $inner[] = "RewriteCond %{HTTP_HOST} ^{$host}\$ [NC]";
                $inner[] = "RewriteRule ^ https://www.{$domain}%{REQUEST_URI} [L,R=301]";
            }
        }
        $sections[] = "<IfModule mod_rewrite.c>\n" . implode("\n", $inner) . "\n</IfModule>";
    }
    if (count($rules) > 0) {
        $lines = ['# Redirects'];
        foreach ($rules as $r) {
            $lines[] = sprintf('Redirect %s %s %s', (string) ($r['code'] ?? ''), (string) ($r['from'] ?? ''), (string) ($r['to'] ?? ''));
        }
        $sections[] = implode("\n", $lines);
    }
    if (count($sections) === 0) {
        return ['output' => '', 'error' => null]; // nothing to generate — NOT an error
    }
    return ['output' => implode("\n\n", [HTACCESS_HEADER, ...$sections]) . "\n", 'error' => null];
}

// Example:
// generate_htaccess([['from' => '/old', 'to' => '/new', 'code' => 301]])['output']
// → "# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n"

if (PHP_SAPI === 'cli' && isset($_SERVER['argv'][0]) && realpath($_SERVER['argv'][0]) === __FILE__) {
    function _check(bool $cond, string $msg): void
    {
        if (!$cond) {
            fwrite(STDERR, "FAIL: {$msg}\n");
            exit(1);
        }
    }
    _check(generate_htaccess([]) === ['output' => '', 'error' => null], 'empty');
    _check(generate_htaccess([['from' => '/old', 'to' => '/new', 'code' => 301]])['output']
        === "# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n", 'redirect');
    $r = generate_htaccess([], ['force_https' => true, 'apex_to_www' => true, 'domain' => 'example.com']);
    _check($r['error'] === null, 'flags not an error');
    _check(str_contains($r['output'], 'RewriteCond %{HTTPS} off'), 'force https');
    _check(str_contains($r['output'], 'RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]'), 'dot escape');
    _check(strpos($r['output'], '# Force HTTPS') < strpos($r['output'], '# Canonical: www domain'), 'section order');
    _check(generate_htaccess([['from' => 'old', 'to' => '/new', 'code' => 301]])['error']
        === 'Rule 1: "from" must be a path starting with / (no spaces)', 'from');
    _check(generate_htaccess([['from' => '/a', 'to' => '  ', 'code' => 301]])['error'] === 'Rule 1: "to" is required', 'to');
    _check(generate_htaccess([['from' => '/a', 'to' => '/b', 'code' => 410]])['error'] === 'Rule 1: code must be 301, 302 or 308', 'code');
    _check(generate_htaccess([['from' => '/a', 'to' => '/b', 'code' => 301], ['from' => '/a', 'to' => '/c', 'code' => 302]])['error']
        === 'Duplicate "from" path: /a', 'duplicate');
    _check(generate_htaccess([], ['www_to_apex' => true, 'apex_to_www' => true, 'domain' => 'e.com'])['error']
        === 'Pick one canonical direction: www→apex or apex→www', 'direction');
    _check(generate_htaccess([], ['www_to_apex' => true])['error'] === 'A domain is required for www canonicalization', 'domain');
    _check(generate_htaccess([], ['www_to_apex' => true, 'domain' => 'https://e.com'])['error']
        === 'Domain must be a bare host, without a protocol', 'protocol');
    echo "all showcase tests passed\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 →