Apache .htaccess generation - HTTPS, www, headers and cache conflicts

Open Tool Apache .htaccess Generator

Apache .htaccess generation - HTTPS, www, headers and cache conflicts

First, the conclusion

Most .htaccess failures are redirect loops, missing modules or HSTS enabled too early. Decide the site host and canonical host before generating. After generating, confirm the target directory AllowOverride permits the directives, run configtest in staging, then curl the status codes and headers. A correct rule still returns 500 when AllowOverride forbids Options, Header or Require.

This page splits HTTPS, www, security headers, compression, cache, 404, hotlink, IP limits (blacklist or allowlist), Basic Auth and WordPress rules into options. It does not write to a server. It outputs reviewable text and lists conflicts and module dependencies.

Rule input fields and feature option groups

When it is useful

  • Move a new site from HTTP to HTTPS and choose www or bare.
  • Add X-Content-Type-Options, X-Frame-Options and Referrer-Policy.
  • Cache static assets for a year and compress text.
  • Block abusive IPs, switch the IP list to allowlist mode, stop image hotlinking or add Basic Auth.
  • Enable WordPress permalinks with an index.php rewrite.

It is not for Nginx, LiteSpeed-specific syntax, CDN edge rules, certificate issuance or password generation. It produces Apache 2.4 .htaccess text only.

Parameters

Enter a hostname such as example.com, without scheme, port or path. HTTPS and www depend on it. Without a host, only a generic HTTPS redirect can be generated; www cannot.

The www choice has three values: none, add www, remove www. Add www sends every non-www host to https://www.example.com; remove www sends every www host to the bare domain.

Security headers start unchecked to avoid locking an incompatible site in one click. HSTS needs working HTTPS first. includeSubDomains requires every subdomain to support HTTPS. Preload is slow to undo and should only be used after a long-term HTTPS decision.

Basic Auth needs an absolute .htpasswd path such as /home/user/.htpasswd. The page does not create passwords or write them into .htaccess. Keep the password file outside the web root.

Steps

  1. Enter the site hostname and choose the www canonical and whether to force HTTPS.
  2. Select security headers, HSTS, a CSP preset, compression, caching, hotlink protection and a 404 as needed.
  3. Configure redirects, IP/CIDR rules and Basic Auth, then click “Generate rules”.
  4. Review the score, conflicts, CSP strength and redirect chain, download .htaccess and run apachectl configtest on the target.

Click Load Sample. The host becomes example.com, with HTTPS, add www, headers, HSTS, compression, cache, hotlink and 404 enabled. Click Generate. The preview shows 38 lines, 2,114 bytes and six modules.

The output starts with Options -Indexes -MultiViews, then a mod_rewrite block with one HTTPS redirect and one www canonical redirect. A reverse-proxy option switches the HTTPS test to X-Forwarded-Proto. Hotlink, headers, compression, cache and 404 follow. The custom /old-page to /new-page redirect is written as Redirect 301.

The line count excludes comments and blank lines. Bytes are UTF-8 text size. The module list comes from actual IfModule blocks, not modules that were never used.

Generated rules, stats and conflict checks

Example one: a redirect loop

If the HTTPS redirect points to https://example.com and the www rule points to https://www.example.com, while a CDN terminates TLS and %{HTTPS} is always off, the browser can bounce between the two rules.

The page's strategy is to send HTTPS directly to the final canonical host and let the www rule handle only a hostname mismatch. An HTTP non-www request reaches the HTTPS canonical host in one hop; an HTTPS non-www request gets one hostname redirect. The rules do not point at each other.

Behind a CDN, %{HTTPS} may be unreliable; use X-Forwarded-Proto instead. The page does not guess the CDN setup. When a loop appears, inspect the forwarded protocol first.

Example two: HSTS and subdomains

HSTS makes the browser remember "HTTPS only" for the max-age. The sample uses one year. includeSubDomains extends the rule to every subdomain; if one has no certificate, users cannot open it.

Preload is a browser preload-list submission, not a local switch. The page warns that removal is slow, but it does not submit anything. Use it only when every subdomain is permanently HTTPS.

Do not enable HSTS on an HTTP site or before the certificate works. The conflict check reports HSTS without HTTPS, but a human still has to confirm the certificate and redirects.

Output

Read the module list first: mod_rewrite for redirects and hotlink, mod_headers for security headers, mod_filter to attach compression by MIME type, mod_deflate for compression, mod_expires for cache, mod_alias for custom redirects. If a module is missing, Apache skips the IfModule block; the page does not fail, but the feature does not work.

Then read the conflict checks: hostname format, www without a host, HSTS without HTTPS, Basic Auth path, IP/CIDR format, 404 path and custom redirect format. Red items must be fixed; amber items are risks, not syntax errors.

Finally, look at line and byte counts. More lines do not mean more security. Duplicate RewriteEngine, duplicate headers and out-of-order Redirect directives add maintenance cost. The page tries to group related rules into one block.

FAQ

"A Header directive always takes effect" is false. A missing mod_headers, a CDN override or PHP setting the same header can change the final response. Always check with curl -I.

"301 is permanent and cannot be undone" is not quite true. Browsers cache it, but a cache clear or another client can recover. Still, validate with 302 first, then switch to 301. The page defaults to 301 for a confirmed canonical move.

"Disabling directory indexes makes a site safe" is false. Options -Indexes only stops listings; direct file access remains. Protect sensitive files with access control, move them outside the web root or delete them.

Performance and concurrency

.htaccess is read per request. More rules add overhead. The page does not encourage enabling everything. Prefer virtual-host configuration when possible and keep .htaccess small.

Compression and cache help static assets, not already-compressed images or video. A one-year cache belongs on versioned or content-hashed assets, not HTML or API responses.

Generation is a local string build with no network and no concurrency risk. The real risk is after deployment: a bad rule can return 500 for every request, so test before replacing the live file.

Security and privacy

The page does not upload config, write to a server or create passwords. Basic Auth writes only the AuthUserFile path; create the password file on the server with htpasswd. Never put passwords, private keys or database credentials in .htaccess.

The sample uses example.com and does not expose a real site. Before copying or downloading, check for internal paths, real IPs or client domains. Redact as needed for external reports.

Deployment checks

The standard flow is backup, upload to staging, apachectl configtest, curl -I, watch logs, then production. Test at least five URLs: HTTP root, HTTPS root, www, non-www and a 404 page.

curl -I http://example.com/
curl -I https://example.com/
curl -I https://www.example.com/
curl -I https://www.example.com/not-found

Expect a 301 to the canonical host, a 200 home page, a 404 custom page and HSTS or X-Content-Type-Options. A 500 means check the Apache error log and restore the backup.

Modules, conflict list and deployment checks

Limits

Apache 2.4 .htaccess text only. The page does not detect installed modules, issue certificates, create .htpasswd passwords, handle Nginx or CDN rules. HSTS preload requires your own submission. Run configtest and curl on the target Apache before going live.

Directive order

Apache processes RewriteRule in order. [L] stops the current round, not the whole request. Put redirects before rewrites so WordPress does not capture the request first.

Redirect and RewriteRule also depend on order. The page puts custom redirects before the WordPress block. If a plugin writes earlier rules, confirm it is not inserting above yours.

RewriteEngine On can repeat inside IfModule blocks, but repeating it in one scope adds nothing. Blocks are split by feature so each can be copied or disabled on its own, not to encourage stacking.

Security headers

X-Content-Type-Options: nosniff stops MIME guessing. It matters for uploads and static files; on a few legacy apps that depend on guessing, it can break rendering.

X-Frame-Options: SAMEORIGIN blocks third-party framing. If the site must be embedded, use CSP frame-ancestors with an explicit allowlist instead.

Referrer-Policy: strict-origin-when-cross-origin sends only the origin cross-site. It is privacy-friendly but affects hotlink checks and analytics that expect a full Referer.

Permissions-Policy disables geolocation, microphone and camera. Browser syntax varies; the page uses a common set. Confirm the actual header after deployment.

HSTS starts at one year; includeSubDomains extends it. Preload is a separate submission, not automatic. Confirm every subdomain before using it.

Cache strategy

mod_expires with one year suits content-hashed assets. HTML, API JSON and changing avatars should not copy that max-age; users would see stale content.

Compression and cache work together. Text benefits from deflate; JPEG, PNG, WebP and MP4 usually do not, and re-compressing wastes CPU.

Behind a CDN, the origin Expires may be overridden. Check the CDN cache policy and the final response, not only the source config.

Basic Auth

Basic Auth is for temporary protection or internal tools, not high-value accounts. Credentials travel in clear text over HTTP, so HTTPS is mandatory. The page does not generate an auth block unless an absolute path is provided.

Create .htpasswd with htpasswd -c and keep it outside the web root. Use 640 or stricter permissions. The page writes only the path and does not verify the file.

A CDN or reverse proxy may cache or bypass auth. Test an unauthenticated request for 401, then confirm a logged-in request works.

WordPress

The permalink rule sends missing files and directories to index.php. It must come after HTTPS and www redirects, or the admin and REST API can be rewritten too early.

Plugins may also write .htaccess. Keep the generated block compatible and avoid duplicate RewriteBase or conflicting rules. Test on staging with cache plugins disabled.

For multisite or a subdirectory install, RewriteBase is not /. The page assumes a single site at the root; adjust manually.

Rollback

Back up the original .htaccess and record owner and permissions. If a rule returns 500, restore the backup and reload Apache; do not comment out lines on production one by one.

Keep the generated README with host, modules, HSTS state and custom redirects. Read it before the next change to avoid duplicate rules.

If only part of the config is needed, deploy in stages: redirects, then headers, then cache. Validate each stage with curl and logs so a failure is easy to isolate.

Compatibility

Apache 2.2 and 2.4 use different access-control syntax. The page uses 2.4 RequireAll and Require not ip; a 2.2 site needs Order/Deny instead.

CDNs may override or strip origin headers. Confirm security headers on the edge response, and move them to CDN rules if the origin cannot pass through.

Basic Auth over HTTP sends credentials in clear text; pair it with HTTPS. Internal tools also need strong passwords and access control. Never place .htpasswd in the web root.

Change checklist

Back up the file, record owner and permissions, upload to staging, run apachectl configtest, reload only after it passes. Do not use a restart as a syntax check.

Use curl -I for HTTP, HTTPS, www, non-www, 404 and static assets. Check Location for redirects, Expires or Cache-Control for cache, and the actual security headers.

Watch the error log for 24 hours for 500, redirect loops and 403. If only images fail, inspect the hotlink Referer rules; if the whole site fails, restore the backup immediately.

1.2.0 addendum: three CSP presets

An all-or-nothing CSP is another common cause of a broken site. This version adds Content-Security-Policy generation with balanced, strict and report-only presets. Balanced allows HTTPS third-party resources, strict allows same-origin only, and report-only emits Content-Security-Policy-Report-Only so blocked resources can be collected first.

The generator flags the mod_headers dependency and enables the balanced preset in the sample. Recommended rollout: observe Report-Only in the browser console, add image, font, analytics and payment callback origins, then switch to enforcement; do not push a strict policy straight to production.

New in 1.3.0: hardening score and pre-deploy simulation

After generating rules, a badge shows an A/B/C/D grade and a 0–100 score. The baseline is fixed at 100: HTTPS 30, HSTS 15, CSP 15, nosniff 8, frame 7, referrer 7, permissions 6, compression 6, cache 6. Report-only CSP counts 7/15, and HSTS scores nothing without forced HTTPS. Basic Auth and IP rules are extra protection and are not scored.

The pre-deploy simulator takes inbound scheme, Host and path and computes the first 301: it applies the mod_rewrite HTTPS and canonical-host steps first, then the mod_alias custom redirect. It catches www.www, an HTTP request that hits a custom path before HTTPS, and a second www hop after the first redirect. A simulation is not a live test; verify with curl -I after deployment.

New in 1.4.0: redirect chain audit

After generating rules, “Redirect chain audit” checks custom redirect syntax, duplicate sources, self-redirects, www.www, prefix shadowing, cycles and chain length, plus the three HSTS preload prerequisites (forced HTTPS, HSTS and includeSubDomains). Findings are graded as errors or warnings with line numbers and reasons.

It makes no network request and only reasons from the current inputs. Before deployment, still run apachectl configtest and verify each 301/302 and target host with curl -I; if a CDN or application layer repeats the redirect, check it at the edge as well.

New in 1.5.0: CSP strength audit

After generating CSP, the audit parses the actual header and checks default-src, object-src, base-uri, frame-ancestors, script-src, style-src, form-action, img-src and connect-src. object-src 'none', base-uri restrictions, frame-ancestors and a script-src without unsafe-inline/unsafe-eval/* carry the most weight.

Report-only mode is capped at B so you observe before enforcing; the strict preset usually scores A while the balanced preset scores B because scripts and styles allow inline code. The audit evaluates the generated string only; nonce, hash, CDN overrides and legacy browsers still affect real execution.

1.5.1: empty by default

The plugin opens with no injected sample input and no automatic parsing; certificate, domain, query and site fields are blank. Use “Load sample” manually to explore; the sample only fills the current page and is not stored as platform default data.

⏫︎