.htaccess Redirect Generator — C++ 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 C++ implementation — the same logic the interactive tool runs, in a shareable, citable form.
// htaccess-generator — Apache .htaccess Redirect Generator. C++ 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, empty error. Never throws on plain input; errors
// travel in the result (error == "" ⇔ TS error: null).
//
// Self-contained: C++ standard library only (std::regex replaces the two TS
// regex literals; no external dependencies). Self-test:
// c++ -DHTACCESS_SELFTEST cpp.cpp -o /tmp/htaccess-cpp && /tmp/htaccess-cpp
#include <cctype>
#include <regex>
#include <set>
#include <string>
#include <vector>
namespace cosmodev {
struct RedirectRule {
std::string from; // must start with "/" and contain no whitespace
std::string to; // absolute URL or a root-relative path
int code = 0; // 301, 302 or 308
};
struct HtaccessOptions {
bool force_https = false;
bool www_to_apex = false; // www.example.com → example.com
bool apex_to_www = false; // example.com → www.example.com
std::string domain; // bare host, required by either www rule
};
struct HtaccessResult {
std::string output;
std::string error; // empty ⇔ TS error: null; non-empty ⇒ output is ""
};
inline std::string trim(const std::string &s) {
size_t b = 0, e = s.size();
while (b < e && std::isspace(static_cast<unsigned char>(s[b]))) b++;
while (e > b && std::isspace(static_cast<unsigned char>(s[e - 1]))) e--;
return s.substr(b, e - b);
}
inline std::string join(const std::vector<std::string> &parts, const std::string &sep) {
std::string out;
for (size_t i = 0; i < parts.size(); ++i) {
if (i) out += sep;
out += parts[i];
}
return out;
}
inline std::string escape_dots(const std::string &s) { // /\./g → "\\."
std::string out;
out.reserve(s.size() * 2);
for (char c : s) {
if (c == '.') out += '\\';
out += c;
}
return out;
}
inline HtaccessResult generate_htaccess(const std::vector<RedirectRule> &rules,
const HtaccessOptions &o = {}) {
static const std::string HEADER = "# Generated by CosmoDev — .htaccess";
static const std::regex WS("\\s"), PROTOCOL("^https?://");
std::set<std::string> seen;
for (size_t i = 0; i < rules.size(); ++i) {
const RedirectRule &r = rules[i];
const std::string head = "Rule " + std::to_string(i + 1) + ": ";
if (r.from.rfind('/', 0) != 0 || std::regex_search(r.from, WS))
return {"", head + "\"from\" must be a path starting with / (no spaces)"};
if (trim(r.to).empty())
return {"", head + "\"to\" is required"};
if (r.code != 301 && r.code != 302 && r.code != 308)
return {"", head + "code must be 301, 302 or 308"};
if (seen.count(r.from))
return {"", "Duplicate \"from\" path: " + r.from};
seen.insert(r.from);
}
if (o.www_to_apex && o.apex_to_www)
return {"", "Pick one canonical direction: www→apex or apex→www"};
const bool wants_www = o.www_to_apex || o.apex_to_www;
if (wants_www && o.domain.empty())
return {"", "A domain is required for www canonicalization"};
if (!o.domain.empty() && std::regex_search(o.domain, PROTOCOL))
return {"", "Domain must be a bare host, without a protocol"};
std::vector<std::string> sections;
if (o.force_https || wants_www) {
std::vector<std::string> inner{"RewriteEngine On"};
if (o.force_https) {
std::vector<std::string> more{"", "# Force HTTPS", "RewriteCond %{HTTPS} off",
"RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]"};
inner.insert(inner.end(), more.begin(), more.end());
}
if (wants_www && !o.domain.empty()) {
const std::string host = escape_dots(o.domain);
inner.push_back("");
inner.push_back(o.www_to_apex ? "# Canonical: apex domain" : "# Canonical: www domain");
if (o.www_to_apex) {
inner.push_back("RewriteCond %{HTTP_HOST} ^www\\." + host + "$ [NC]");
inner.push_back("RewriteRule ^ https://" + o.domain + "%{REQUEST_URI} [L,R=301]");
} else {
inner.push_back("RewriteCond %{HTTP_HOST} ^" + host + "$ [NC]");
inner.push_back("RewriteRule ^ https://www." + o.domain + "%{REQUEST_URI} [L,R=301]");
}
}
sections.push_back("<IfModule mod_rewrite.c>\n" + join(inner, "\n") + "\n</IfModule>");
}
if (!rules.empty()) {
std::vector<std::string> lines{"# Redirects"};
for (const RedirectRule &r : rules)
lines.push_back("Redirect " + std::to_string(r.code) + " " + r.from + " " + r.to);
sections.push_back(join(lines, "\n"));
}
if (sections.empty())
return {"", ""}; // nothing to generate — NOT an error
std::string out = HEADER;
for (const std::string &s : sections) out += "\n\n" + s;
return {out + "\n", ""};
}
} // namespace cosmodev
#ifdef HTACCESS_SELFTEST
#include <cassert>
#include <iostream>
int main() {
using namespace cosmodev;
auto r1 = generate_htaccess({});
assert(r1.output.empty() && r1.error.empty());
auto r2 = generate_htaccess({RedirectRule{"/old", "/new", 301}});
assert(r2.error.empty());
assert(r2.output == "# Generated by CosmoDev — .htaccess\n\n# Redirects\nRedirect 301 /old /new\n");
HtaccessOptions w;
w.force_https = true;
w.apex_to_www = true;
w.domain = "example.com";
auto r3 = generate_htaccess({}, w);
assert(r3.error.empty());
assert(r3.output.find("RewriteCond %{HTTPS} off") != std::string::npos);
assert(r3.output.find("RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]") != std::string::npos);
assert(r3.output.find("RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]") != std::string::npos);
assert(r3.output.find("# Force HTTPS") < r3.output.find("# Canonical: www domain"));
auto r4 = generate_htaccess({RedirectRule{"old", "/new", 301}});
assert(r4.output.empty() && r4.error == "Rule 1: \"from\" must be a path starting with / (no spaces)");
assert(generate_htaccess({RedirectRule{"/a", " ", 301}}).error == "Rule 1: \"to\" is required");
assert(generate_htaccess({RedirectRule{"/a", "/b", 410}}).error == "Rule 1: code must be 301, 302 or 308");
assert(generate_htaccess({RedirectRule{"/a", "/b", 301}, RedirectRule{"/a", "/c", 302}}).error ==
"Duplicate \"from\" path: /a");
HtaccessOptions both;
both.www_to_apex = both.apex_to_www = true;
both.domain = "e.com";
assert(generate_htaccess({}, both).error == "Pick one canonical direction: www→apex or apex→www");
HtaccessOptions no_domain;
no_domain.www_to_apex = true;
assert(generate_htaccess({}, no_domain).error == "A domain is required for www canonicalization");
HtaccessOptions proto;
proto.www_to_apex = true;
proto.domain = "https://e.com";
assert(generate_htaccess({}, proto).error == "Domain must be a bare host, without a protocol");
std::cout << "all showcase tests passed" << std::endl;
return 0;
}
#endif
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 →