.htaccess Generator
Generate an Apache .htaccess draft from presets and ordered rule sections, then review warnings, counts, and saved JSON before staging changes.Apache sites often need request rules in a place where the main server configuration is not available. A shared-hosting account may need HTTPS redirects, a content folder may need directory listings disabled, or a small app may need cache headers, custom error pages, and a fallback route without asking the server administrator to edit the virtual host. A .htaccess file is Apache's directory-level way to do that work.
The file is powerful because it sits beside the content it affects. Directives placed in one directory can apply to that directory and its descendants, so a small text file can change redirects, response headers, MIME handling, access rules, and file lookup behavior for a whole subtree. That same locality is also why review matters: a rule that belongs in the site root may be wrong inside a subfolder, and a parent directory may already be applying another rule before the local file is read.
| Concept | Plain meaning | Why it changes the draft |
|---|---|---|
| Distributed configuration | Apache reads configuration from a directory-level file during request handling. | The same directive can behave differently depending on where the file is placed. |
| Override policy | The host decides which directive groups are honored from .htaccess. |
A clean-looking file can be ignored or rejected if the needed override class is unavailable. |
| Rewrite context | Per-directory rewrite rules are evaluated relative to the current directory. | Leading slashes, base paths, and fallback targets need extra care for subfolder apps. |
| Browser policy headers | Headers such as HSTS, CSP, CORS, and Cache-Control tell browsers how to treat responses. | A strict policy can improve safety or performance, but it can also block assets, APIs, or old links. |
Rule order is the source of many surprises. Redirects can stop a request before later header rules are visible to the browser. A maintenance rewrite can catch a health-check path if the exception is missing. A single-page app fallback can accidentally serve index.html for a missing image when file and directory guards are wrong. The safest draft keeps routing choices near the top, policy headers and cache rules readable, and raw custom directives isolated for review.
A directory-level file should be treated as a deployment change, not as a harmless text snippet. HSTS can commit browsers to HTTPS for a long time, CORS can decide which browser origins may read an API response, and cache lifetimes can keep stale files alive after a release. The file may be small, but it deserves the same staging, rollback, and log review as any other web-server change.
How to Use This Tool:
Start from the site shape, then work through the generated sections until the final text matches the directory you plan to change.
- Choose Static site, Single-page app, API backend, Hardened headers, or Custom in Preset. The section list should update immediately, and the summary should show a nonzero directive count when active sections emit rules.
- Enter the canonical host in Domain. Use a bare host such as
www.example.com; do not include a protocol or path. This value feeds HTTPS redirects, host canonicalization, hotlink protection, and CORS defaults. - Set the top-level switches before editing individual rows. Force HTTPS, App base path, Include comments, Legacy browser headers, and HSTS preload change generated output across more than one section.
- Use Add section for any missing block, then open each row to edit its Apache choices. Review redirect status codes, cache TTLs, CSP strength, CORS origin, maintenance exceptions, IP lists, PHP directives, MIME mappings, and any Raw Snippet text.
- Drag rows into the order you want Apache to evaluate. Put request-moving rules such as forced HTTPS, canonical host redirects, maintenance mode, and hotlink blocking before lower-risk header, cache, and file-behavior blocks unless your deployment needs a different order.
- Read the summary status and warning text. Fix loops, missing domains, suspicious redirect paths, HSTS preload mismatches, empty error-document sections, or a removed Force HTTPS section before copying the final file.
- Open the .htaccess result tab and inspect the text line by line. Use Rule Summary for counts and review exports, and use JSON or the copied link only when you need to preserve or share the draft choices.
Interpreting Results:
The .htaccess tab is the deployable draft. The Rule Summary tab is a review aid: Rules (non-comment) counts active nonblank lines that are not comments, Section comments counts labeled groups, Total lines shows the visible text length in lines, Bytes estimates export size, and Warnings shows the number of issues detected by the page.
A clean warning count does not prove the file will work on the target host. It only means the known checks did not catch a missing domain, obvious redirect mistake, HSTS preload mismatch, empty 404/403 setup, or removed HTTPS section. Real behavior still depends on Apache modules, override policy, parent configuration, certificates, existing files, and the directory where the file is uploaded.
| Result cue | What it means | Follow-up check |
|---|---|---|
| Check warnings | At least one draft choice looks risky or incomplete. | Resolve the warning before treating the .htaccess text as ready for staging. |
| Low rule count after a large preset | Several sections may be disabled, empty, or producing comments only. | Open the collapsed section rows and confirm the badges match the intended site policy. |
| High rule count with many rewrites | Routing order is now a real review item. | Test old URLs, deep links, assets, health paths, and error pages in a staging directory. |
| Share link or JSON copied | The draft choices may include hosts, access lists, maintenance bypass keys, and policy details. | Share only with people who should see deployment configuration. |
After copying the file, stage it in the narrowest directory possible. A 500 error usually points to syntax or an unpermitted directive; a page that still behaves as before often points to missing override permission, a disabled Apache module, or another configuration layer taking precedence.
Technical Details:
Apache treats .htaccess as distributed configuration. When enabled, the server checks relevant directories during request processing, merges allowed directives with the main configuration, and applies those directives in directory context. The host's AllowOverride or AllowOverrideList policy controls which directive families are accepted, so support for one directive does not imply support for every other directive in the file.
Per-directory rewrite rules have a different shape from virtual-host rewrite rules. Apache strips the directory prefix before matching a RewriteRule, while conditions can still inspect request variables such as host, HTTPS state, request URI, query string, referrer, and remote address. That is why base paths, leading slashes, and exception conditions need careful review when a file is used below the site root.
Rule Core:
The draft is assembled from an ordered list of enabled or populated sections. Each section contributes a block only when its settings produce Apache text; comments can label blocks for review without changing request behavior.
| Section family | Representative directives | Main review question |
|---|---|---|
| Routing and redirects | RewriteEngine, RewriteCond, RewriteRule, Redirect, and RedirectMatch. |
Can the rule loop, catch the wrong path, or fire before a needed exception? |
| Headers and cache policy | Header, ExpiresActive, ExpiresByType, and Cache-Control. |
Do browser policy, HSTS scope, CORS access, and cache lifetime match the release plan? |
| Access and availability | Require ip, ErrorDocument, maintenance rewrites, and Retry-After. |
Are trusted users, health checks, and custom error pages still reachable? |
| Directory and file handling | Options, DirectoryIndex, AddType, AddEncoding, and PHP value directives. |
Does the host allow these directives in this directory, and do they conflict with parent settings? |
Formula Core:
The summary metrics are mechanical checks on the generated text. They are useful for review drift, not for proving server correctness.
Here R is the displayed non-comment rule count. The byte metric is the UTF-8 byte length of the generated text, so comments and whitespace increase size even when they do not add active Apache directives.
Policy Boundaries:
| Policy area | Technical boundary | Staging test |
|---|---|---|
| HSTS and preload | Long max-age values and preload affect future browser connections, and preload requires HTTPS readiness across the host surface. | Confirm certificate coverage, forced HTTPS, subdomain readiness, and rollback expectations before keeping preload. |
| CORS | Credentialed browser requests need a specific origin rather than a wildcard origin. | Test the real web origin, methods, request headers, and browser console output. |
| CSP | Strict content policies can block scripts, styles, images, frames, or API connections that are not named by policy. | Load important pages and check blocked-resource messages before switching from relaxed discovery to strict policy. |
| Cache-Control | Long lifetimes and immutable fit versioned assets, not files that change under the same name. |
Deploy a staged asset update and confirm the browser receives the expected new file. |
| Raw directives | Unreviewed custom lines bypass the structured section safeguards. | Check Apache documentation for each directive's context and override requirement. |
The generated text cannot discover the target host's modules, certificate state, parent rules, or override classes. Pair the draft with a server config test when available, a narrow staging upload when not, and an error-log check after the first request.
Limitations and Privacy Notes:
The draft text is assembled in the browser from the selected controls. The page does not run Apache, inspect the target server, or prove that a host will honor every directive.
- Use the main Apache configuration instead of
.htaccesswhen you control the server and the rule is stable. - Do not treat a clean Warnings count as a security approval or deployment approval.
- Review copied links and JSON before sharing because they can reveal domains, policy choices, IP rules, bypass parameters, and custom directives.
- Test HSTS, CSP, CORS, cache, redirect, and maintenance behavior in staging before changing a production directory.
Worked Examples:
Shared-host static site
A brochure site at www.example.com needs HTTPS, one canonical host, asset caching, hotlink protection, and custom error pages. Choose Static site, keep Force HTTPS on, set Domain to www.example.com, and review Rule Summary. A useful first pass should show active Rules (non-comment), Warnings at 0, and readable section comments in the .htaccess tab.
Single-page app under a subpath
An app mounted at /portal needs direct deep links such as /portal/settings to load without hiding real files. Choose Single-page app, set App base path to /portal, and inspect the generated rewrite block in .htaccess. In staging, test a valid deep link, a real CSS or image file, and a missing asset path before accepting the fallback.
Redirect mistake caught before upload
A custom redirect row with From set to old-page and To set to old-page should raise a warning because the source and target match, and the source path does not start with /. Fix the row to something like /old-page -> /new-page, then confirm Warnings returns to 0 before copying the final text.
HSTS preload review
A launch hardening pass turns on Hardened headers and HSTS preload. If Domain is blank or Force HTTPS is off, the warning count should increase. Keep preload only after the base domain, www, and all subdomains that matter have valid HTTPS and the team accepts that browser preload removal can take time.
FAQ:
Can I upload the generated file as-is?
Only after staging and review. The .htaccess text may be well formed but still fail if the directory disallows the directive class or the needed Apache module is unavailable.
Why did a rule that worked in virtual host config fail here?
Per-directory rewrite rules use directory-relative matching, so patterns and substitutions often need different leading slashes or a RewriteBase when moved into .htaccess.
What does a 500 error after upload usually mean?
Check the Apache error log first. Common causes are syntax errors, directives that are not allowed in .htaccess, or directives that need an override class the host has not enabled.
Should I use wildcard CORS with credentials?
No. If Credentialed CORS is on, use a specific Allowed origin such as https://app.example.com, then test the browser request and console output.
Is the JSON output the server file?
No. Apache reads the generated .htaccess text. The JSON tab records the selected sections and options for review or handoff.
Glossary:
- AllowOverride
- The Apache directive that controls which classes of directory-level directives may be honored.
- CORS
- Cross-Origin Resource Sharing, the browser mechanism that decides which origins may read a response.
- CSP
- Content Security Policy, a response header that limits where scripts, styles, images, and other resources may load from.
- HSTS
- HTTP Strict Transport Security, a response header that tells browsers to use HTTPS for a host for a set time.
- RewriteRule
- An Apache directive that can redirect or internally rewrite a request when its pattern and conditions match.
- Cache-Control
- An HTTP header that tells browsers and caches how long a response may be reused.
References:
- Apache HTTP Server Tutorial: .htaccess files, Apache HTTP Server Project.
- Apache Module mod_rewrite, Apache HTTP Server Project.
- HSTS Preload List Submission, hstspreload.org.
- Strict-Transport-Security header, MDN Web Docs, April 23, 2026.
- Cross-Origin Resource Sharing (CORS), MDN Web Docs, November 30, 2025.
- Content Security Policy (CSP), MDN Web Docs, March 22, 2026.