Skip to content

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

// htaccess-generator — Apache .htaccess Redirect Generator. Java 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.
//
// Self-contained: JDK standard library only (no external jars).
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

// Package-private: display snippets keep the repo filename (java.java),
// which need not match the class name.
final class HtaccessGenerator {

    /** One redirect: from must start with "/" and contain no whitespace;
     *  to is an absolute URL or a root-relative path; code is 301/302/308
     *  (anything else is rejected at runtime, mirroring the TS union guard). */
    static final class RedirectRule {
        final String from;
        final String to;
        final int code;
        RedirectRule(String from, String to, int code) {
            this.from = from;
            this.to = to;
            this.code = code;
        }
    }

    /** Options; the zero-arg constructor mirrors TS generateHtaccess(rules, {}). */
    static final class Options {
        boolean forceHttps = false;
        boolean wwwToApex = false; // www.example.com → example.com
        boolean apexToWww = false; // example.com → www.example.com
        String domain = "";        // bare host, required by either www rule
    }

    /** TS HtaccessResult union: error == null ⇔ error: null; a non-null
     *  error always comes with an empty output. */
    static final class Result {
        final String output;
        final String error;
        Result(String output, String error) {
            this.output = output;
            this.error = error;
        }
    }

    private static final String HEADER = "# Generated by CosmoDev — .htaccess";

    private static boolean hasWhitespace(String s) {
        for (int i = 0; i < s.length(); i++) {
            if (Character.isWhitespace(s.charAt(i))) return true;
        }
        return false;
    }

    /** Generate .htaccess content from rules and options. Twin of
     *  generateHtaccess() in src/lib/htaccess-generator.ts. */
    static Result generate(RedirectRule[] rules, Options o) {
        Set<String> seen = new HashSet<>();
        for (int i = 0; i < rules.length; i++) {
            RedirectRule r = rules[i];
            String from = r.from == null ? "" : r.from;
            String to = r.to == null ? "" : r.to;
            if (!from.startsWith("/") || hasWhitespace(from)) {
                return new Result("", "Rule " + (i + 1) + ": \"from\" must be a path starting with / (no spaces)");
            }
            if (to.trim().isEmpty()) {
                return new Result("", "Rule " + (i + 1) + ": \"to\" is required");
            }
            if (r.code != 301 && r.code != 302 && r.code != 308) {
                return new Result("", "Rule " + (i + 1) + ": code must be 301, 302 or 308");
            }
            if (!seen.add(from)) {
                return new Result("", "Duplicate \"from\" path: " + from);
            }
        }
        if (o == null) o = new Options();
        String domain = o.domain == null ? "" : o.domain;
        if (o.wwwToApex && o.apexToWww) {
            return new Result("", "Pick one canonical direction: www→apex or apex→www");
        }
        boolean wantsWww = o.wwwToApex || o.apexToWww;
        if (wantsWww && domain.isEmpty()) {
            return new Result("", "A domain is required for www canonicalization");
        }
        if (!domain.isEmpty() && (domain.startsWith("http://") || domain.startsWith("https://"))) {
            return new Result("", "Domain must be a bare host, without a protocol");
        }

        List<String> sections = new ArrayList<>();
        if (o.forceHttps || wantsWww) {
            List<String> inner = new ArrayList<>(List.of("RewriteEngine On"));
            if (o.forceHttps) {
                inner.addAll(List.of("", "# Force HTTPS", "RewriteCond %{HTTPS} off",
                        "RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]"));
            }
            if (wantsWww && !domain.isEmpty()) {
                String host = domain.replace(".", "\\."); // /\./g → "\\."
                inner.add("");
                inner.add("# Canonical: " + (o.wwwToApex ? "apex domain" : "www domain"));
                if (o.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) {
            List<String> lines = new ArrayList<>(List.of("# Redirects"));
            for (RedirectRule r : rules) {
                lines.add("Redirect " + r.code + " " + r.from + " " + r.to);
            }
            sections.add(String.join("\n", lines));
        }
        if (sections.isEmpty()) {
            return new Result("", null); // nothing to generate — NOT an error
        }
        List<String> parts = new ArrayList<>(List.of(HEADER));
        parts.addAll(sections);
        return new Result(String.join("\n\n", parts) + "\n", null);
    }

    /** Showcase tests: javac java.java && java HtaccessGenerator */
    public static void main(String[] args) {
        check(generate(new RedirectRule[0], new Options()).output.isEmpty(), "empty");
        Result r = generate(new RedirectRule[] { new RedirectRule("/old", "/new", 301) }, new Options());
        check(r.output.equals("# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n"), "redirect");
        Options w = new Options();
        w.forceHttps = true;
        w.apexToWww = true;
        w.domain = "example.com";
        Result c = generate(new RedirectRule[0], w);
        check(c.error == null && c.output.contains("RewriteCond %{HTTPS} off"), "force https");
        check(c.output.contains("RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]"), "dot escape");
        check(c.output.contains("RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]"), "www rule");
        check(c.output.indexOf("# Force HTTPS") < c.output.indexOf("# Canonical: www domain"), "section order");
        Result bad = generate(new RedirectRule[] { new RedirectRule("old", "/new", 301) }, new Options());
        check("Rule 1: \"from\" must be a path starting with / (no spaces)".equals(bad.error), "from");
        Result blank = generate(new RedirectRule[] { new RedirectRule("/a", "  ", 301) }, new Options());
        check("Rule 1: \"to\" is required".equals(blank.error), "to");
        Result badCode = generate(new RedirectRule[] { new RedirectRule("/a", "/b", 410) }, new Options());
        check("Rule 1: code must be 301, 302 or 308".equals(badCode.error), "code");
        Result dup = generate(new RedirectRule[] { new RedirectRule("/a", "/b", 301), new RedirectRule("/a", "/c", 302) }, new Options());
        check("Duplicate \"from\" path: /a".equals(dup.error), "duplicate");
        Options both = new Options();
        both.wwwToApex = true;
        both.apexToWww = true;
        both.domain = "e.com";
        check("Pick one canonical direction: www→apex or apex→www".equals(generate(new RedirectRule[0], both).error), "direction");
        Options noDomain = new Options();
        noDomain.wwwToApex = true;
        check("A domain is required for www canonicalization".equals(generate(new RedirectRule[0], noDomain).error), "no domain");
        Options proto = new Options();
        proto.wwwToApex = true;
        proto.domain = "https://e.com";
        check("Domain must be a bare host, without a protocol".equals(generate(new RedirectRule[0], proto).error), "protocol");
        System.out.println("all showcase tests passed");
    }

    private static void check(boolean ok, String label) {
        if (!ok) throw new AssertionError("FAILED: " + label);
    }
}

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 →