.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; live Go twin:
* cli/htaccess-generator/htaccess-generator.go — kept in lock-step.)
*
* 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, UTF-8 bytes).
* Validation runs in the TS order and the first failure wins. No rules and
* no flags is NOT an error — empty output, error NULL. NULL fields read as
* ""; errors are heap strings the caller frees (alongside output).
*
* Self-contained: C stdlib only. Build + self-test:
* cc -DHTACCESS_SELFTEST c.c -o /tmp/htaccess-c && /tmp/htaccess-c
*/
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { const char *from, *to; int code; } HtRule;
typedef struct { int force_https, www_to_apex, apex_to_www; const char *domain; } HtOptions;
typedef struct { char *output; char *error; } HtResult; /* error NULL ⇔ TS error: null */
static const char HEADER[] = "# Generated by CosmoDev — .htaccess";
static char *ht_strdup(const char *s) {
size_t n = strlen(s) + 1;
char *p = malloc(n);
if (p) memcpy(p, s, n);
return p;
}
static char *ht_fmt(const char *fmt, ...) {
char tmp[192];
va_list ap;
va_start(ap, fmt);
vsnprintf(tmp, sizeof tmp, fmt, ap);
va_end(ap);
return ht_strdup(tmp);
}
/* /\s/ on single bytes. */
static int ht_ws(const char *s) {
for (; *s; s++)
if (isspace((unsigned char)*s)) return 1;
return 0;
}
/* JS String.prototype.trim() == "". */
static int ht_blank(const char *s) {
while (*s && isspace((unsigned char)*s)) s++;
return *s == '\0';
}
/* /\./g → '\\.': backslash-escape every dot in the bare host. */
static char *ht_escape_dots(const char *domain) {
size_t n = strlen(domain), j = 0;
char *out = malloc(2 * n + 1);
if (!out) return NULL;
for (size_t i = 0; i < n; i++) {
if (domain[i] == '.') out[j++] = '\\';
out[j++] = domain[i];
}
out[j] = '\0';
return out;
}
/* Growable text buffer. */
typedef struct { char *s; size_t len, cap; } HtBuf;
static int ht_put(HtBuf *b, const char *s) {
size_t n = strlen(s);
if (b->len + n + 1 > b->cap) {
size_t cap = b->cap ? b->cap : 256;
while (cap < b->len + n + 1) cap *= 2;
char *p = realloc(b->s, cap);
if (!p) return 0;
b->s = p;
b->cap = cap;
}
memcpy(b->s + b->len, s, n + 1);
b->len += n;
return 1;
}
HtResult htaccess_generate(const HtRule *rules, size_t nrules, const HtOptions *o) {
HtResult r = { NULL, NULL };
char *section[2] = { NULL, NULL }; /* max two: IfModule block + Redirects */
size_t nsec = 0;
for (size_t i = 0; i < nrules; i++) {
const char *f = rules[i].from ? rules[i].from : "";
const char *t = rules[i].to ? rules[i].to : "";
if (f[0] != '/' || ht_ws(f)) {
r.error = ht_fmt("Rule %lu: \"from\" must be a path starting with / (no spaces)", (unsigned long)(i + 1));
return r;
}
if (ht_blank(t)) {
r.error = ht_fmt("Rule %lu: \"to\" is required", (unsigned long)(i + 1));
return r;
}
if (rules[i].code != 301 && rules[i].code != 302 && rules[i].code != 308) {
r.error = ht_fmt("Rule %lu: code must be 301, 302 or 308", (unsigned long)(i + 1));
return r;
}
for (size_t j = 0; j < i; j++) {
const char *g = rules[j].from ? rules[j].from : "";
if (strcmp(g, f) == 0) {
r.error = ht_fmt("Duplicate \"from\" path: %s", f);
return r;
}
}
}
int force_https = o && o->force_https;
int www_to_apex = o && o->www_to_apex;
int apex_to_www = o && o->apex_to_www;
const char *domain = (o && o->domain) ? o->domain : "";
if (www_to_apex && apex_to_www) {
r.error = ht_strdup("Pick one canonical direction: www→apex or apex→www");
return r;
}
int wants_www = www_to_apex || apex_to_www;
if (wants_www && domain[0] == '\0') {
r.error = ht_strdup("A domain is required for www canonicalization");
return r;
}
if (domain[0] && (strncmp(domain, "http://", 7) == 0 || strncmp(domain, "https://", 8) == 0)) {
r.error = ht_strdup("Domain must be a bare host, without a protocol");
return r;
}
if (force_https || wants_www) {
HtBuf b = { NULL, 0, 0 };
int ok = ht_put(&b, "<IfModule mod_rewrite.c>\nRewriteEngine On");
if (ok && force_https)
ok = ht_put(&b, "\n\n# Force HTTPS\nRewriteCond %{HTTPS} off\n"
"RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]");
if (ok && wants_www && domain[0]) {
char *host = ht_escape_dots(domain);
ok = host != NULL && ht_put(&b, "\n\n# Canonical: ") &&
ht_put(&b, www_to_apex ? "apex domain" : "www domain") && ht_put(&b, "\n");
if (ok && www_to_apex)
ok = ht_put(&b, "RewriteCond %{HTTP_HOST} ^www\\.") && ht_put(&b, host) &&
ht_put(&b, "$ [NC]\nRewriteRule ^ https://") && ht_put(&b, domain) &&
ht_put(&b, "%{REQUEST_URI} [L,R=301]");
else if (ok)
ok = ht_put(&b, "RewriteCond %{HTTP_HOST} ^") && ht_put(&b, host) &&
ht_put(&b, "$ [NC]\nRewriteRule ^ https://www.") && ht_put(&b, domain) &&
ht_put(&b, "%{REQUEST_URI} [L,R=301]");
free(host);
}
ok = ok && ht_put(&b, "\n</IfModule>");
if (!ok) { free(b.s); goto oom; }
section[nsec++] = b.s;
}
if (nrules > 0) {
HtBuf b = { NULL, 0, 0 };
int ok = ht_put(&b, "# Redirects");
for (size_t k = 0; ok && k < nrules; k++) {
char line[640];
snprintf(line, sizeof line, "\nRedirect %d %s %s", rules[k].code,
rules[k].from ? rules[k].from : "", rules[k].to ? rules[k].to : "");
ok = ht_put(&b, line);
}
if (!ok) { free(b.s); goto oom; }
section[nsec++] = b.s;
}
if (nsec == 0) { /* nothing to generate — empty output is NOT an error */
r.output = ht_strdup("");
return r;
}
{ /* output = HEADER + "\n\n" + section[0] [+ "\n\n" + section[1]] + "\n" */
size_t n = strlen(HEADER) + 4;
for (size_t i = 0; i < nsec; i++) n += strlen(section[i]) + 2;
char *out = malloc(n);
if (!out) goto oom;
strcpy(out, HEADER);
strcat(out, "\n\n");
for (size_t i = 0; i < nsec; i++) {
strcat(out, section[i]);
strcat(out, i + 1 < nsec ? "\n\n" : "\n");
}
free(section[0]);
free(section[1]);
r.output = out;
return r;
}
oom:
free(section[0]);
free(section[1]);
r.error = ht_strdup("out of memory");
return r;
}
#ifdef HTACCESS_SELFTEST
#include <assert.h>
int main(void) {
HtOptions o = { 0, 0, 0, NULL };
HtResult r = htaccess_generate(NULL, 0, &o);
assert(r.error == NULL && r.output && r.output[0] == '\0');
free(r.output);
HtRule rules[] = { { "/old", "/new", 301 }, { "/a", "https://x.dev/y", 308 } };
r = htaccess_generate(rules, 2, &o);
assert(r.error == NULL);
assert(strcmp(r.output, HEADER "\n\n# Redirects\nRedirect 301 /old /new\n"
"Redirect 308 /a https://x.dev/y\n") == 0);
free(r.output);
HtOptions w = { 1, 0, 1, "example.com" }; /* force_https + apex→www */
r = htaccess_generate(NULL, 0, &w);
assert(r.error == NULL);
const char *https_at = strstr(r.output, "# Force HTTPS");
const char *canon_at = strstr(r.output, "# Canonical: www domain");
assert(https_at && canon_at && https_at < canon_at);
assert(strstr(r.output, "RewriteCond %{HTTP_HOST} ^example\\.com$ [NC]"));
assert(strstr(r.output, "RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]"));
free(r.output);
HtRule bad[] = { { "old", "/new", 301 } };
r = htaccess_generate(bad, 1, &o);
assert(r.output && r.output[0] == '\0');
assert(strcmp(r.error, "Rule 1: \"from\" must be a path starting with / (no spaces)") == 0);
free(r.output);
free(r.error);
printf("all showcase tests passed\n");
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 →