.htaccess Redirect Generator — Ruby 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 Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.
# frozen_string_literal: true
# htaccess-generator — Apache .htaccess Redirect Generator. Ruby 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, nil error. Never raises on odd input: nil fields read
# as '', errors travel in the result hash.
HEADER = '# Generated by CosmoDev — .htaccess'
# rules: [{ from:, to:, code: }]; options: { force_https:, www_to_apex:,
# apex_to_www:, domain: }. Returns { output: String, error: String | nil }.
def generate_htaccess(rules, options = {})
seen = []
rules.each_with_index do |r, i|
from = r[:from].to_s
to = r[:to].to_s
code = r[:code]
if !from.start_with?('/') || from.match?(/\s/)
return { output: '', error: "Rule #{i + 1}: \"from\" must be a path starting with / (no spaces)" }
end
return { output: '', error: "Rule #{i + 1}: \"to\" is required" } if to.strip.empty?
unless [301, 302, 308].include?(code)
return { output: '', error: "Rule #{i + 1}: code must be 301, 302 or 308" }
end
return { output: '', error: "Duplicate \"from\" path: #{from}" } if seen.include?(from)
seen << from
end
force_https = !!options[:force_https]
www_to_apex = !!options[:www_to_apex]
apex_to_www = !!options[:apex_to_www]
domain = options[:domain].to_s
if www_to_apex && apex_to_www
return { output: '', error: 'Pick one canonical direction: www→apex or apex→www' }
end
wants_www = www_to_apex || apex_to_www
return { output: '', error: 'A domain is required for www canonicalization' } if wants_www && domain.empty?
if !domain.empty? && domain.match?(%r{\Ahttps?://})
return { output: '', error: 'Domain must be a bare host, without a protocol' }
end
sections = []
if force_https || wants_www
inner = ['RewriteEngine On']
if force_https
inner += ['', '# Force HTTPS', 'RewriteCond %{HTTPS} off',
'RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]']
end
if wants_www && !domain.empty?
host = domain.gsub('.') { '\.' } # /\./g → '\.' (block form: literal replacement)
inner += ['', "# Canonical: #{www_to_apex ? 'apex domain' : 'www domain'}"]
if www_to_apex
inner += ["RewriteCond %{HTTP_HOST} ^www\\.#{host}$ [NC]",
"RewriteRule ^ https://#{domain}%{REQUEST_URI} [L,R=301]"]
else
inner += ["RewriteCond %{HTTP_HOST} ^#{host}$ [NC]",
"RewriteRule ^ https://www.#{domain}%{REQUEST_URI} [L,R=301]"]
end
end
sections << "<IfModule mod_rewrite.c>\n#{inner.join("\n")}\n</IfModule>"
end
unless rules.empty?
sections << (['# Redirects'] + rules.map { |r| "Redirect #{r[:code]} #{r[:from]} #{r[:to]}" }).join("\n")
end
return { output: '', error: nil } if sections.empty? # not an error
{ output: ([HEADER] + sections).join("\n\n") + "\n", error: nil }
end
# Example:
# generate_htaccess([{ from: '/old', to: '/new', code: 301 }])[:output]
# => "# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n"
if __FILE__ == $PROGRAM_NAME
g = ->(rules, opts = {}) { generate_htaccess(rules, opts) }
raise 'empty' unless g.call([]) == { output: '', error: nil }
out = g.call([{ from: '/old', to: '/new', code: 301 }])[:output]
raise 'redirect' unless out == "# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n"
r = g.call([], force_https: true, apex_to_www: true, domain: 'example.com')
raise 'https' unless r[:error].nil? &&
r[:output].include?('RewriteCond %{HTTP_HOST} ^example\.com$ [NC]') &&
r[:output].index('# Force HTTPS') < r[:output].index('# Canonical: www domain')
raise 'from' unless g.call([{ from: 'old', to: '/new', code: 301 }])[:error] ==
'Rule 1: "from" must be a path starting with / (no spaces)'
raise 'to' unless g.call([{ from: '/a', to: ' ', code: 301 }])[:error] == 'Rule 1: "to" is required'
raise 'code' unless g.call([{ from: '/a', to: '/b', code: 410 }])[:error] == 'Rule 1: code must be 301, 302 or 308'
raise 'dup' unless g.call([{ from: '/a', to: '/b', code: 301 }, { from: '/a', to: '/c', code: 302 }])[:error] ==
'Duplicate "from" path: /a'
raise 'dir' unless g.call([], www_to_apex: true, apex_to_www: true, domain: 'e.com')[:error] ==
'Pick one canonical direction: www→apex or apex→www'
raise 'nodomain' unless g.call([], www_to_apex: true)[:error] == 'A domain is required for www canonicalization'
raise 'proto' unless g.call([], www_to_apex: true, domain: 'https://e.com')[:error] ==
'Domain must be a bare host, without a protocol'
puts 'all showcase tests passed'
end
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 →