.htaccess Generator
Build an Apache .htaccess draft for redirects, headers, caching, CORS, and access rules with warnings and copy-ready output before staging.Apache directory rules usually appear when a site owner needs server behavior changed without direct access to the main virtual host. A shared-hosting site may need all traffic forced to HTTPS, a download folder may need directory listings blocked, or an app under a subpath may need deep links routed back to one entry file. A .htaccess file is the small, local configuration file Apache can read inside the affected directory.
That local placement is useful, but it changes how rules should be reviewed. Directives in one directory can apply to the files and folders below it, while parent configuration and the host's override policy still decide what is allowed. The same redirect or header rule can be safe at the site root and wrong in a nested folder, especially when rewrite patterns, relative paths, and fallback targets are involved.
| Concept | Plain meaning | Why it changes the draft |
|---|---|---|
| Distributed configuration | Apache reads configuration from a directory-level file during request handling. | Placement changes which paths are matched and which descendants inherit the rule. |
| Override policy | The host decides which directive groups are honored from .htaccess. |
A valid-looking rule can be ignored or rejected when 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 below the site root. |
| 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 causes many deployment surprises. Redirects can end a request before later headers are visible. A maintenance rewrite can catch a health-check path when the exception is missing. A single-page app fallback can accidentally serve index.html for a missing image if real-file and real-directory guards are missing. A safer draft keeps request-moving rules near the top, groups policy headers and cache directives clearly, and leaves custom raw lines easy to inspect.
Small configuration files still carry production risk. HSTS can commit browsers to HTTPS for a long period, CORS controls which browser origins may read responses, and cache lifetimes can keep stale assets alive after a release. Treat a directory-level Apache change like any other server change: stage it narrowly, keep a rollback path, and read the error log after the first request.
How to Use This Tool:
Start from the site shape, then work through the generated sections until the final text matches the directory and host 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 the deployment has a deliberate exception.
- 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, an obvious redirect mistake, an HSTS preload mismatch, an empty 404/403 setup, or a 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 the feature is 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 removes 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. Base paths, leading slashes, and exception conditions therefore 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 the app's exact HTTPS origin rather than a wildcard, 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.
- How to disable directory listing in Apache, simplified.guide.
- How to deny access to sensitive files in Apache, simplified.guide.
- HSTS Preload List Submission, hstspreload.org.
- Strict-Transport-Security header, MDN Web Docs.
- Cross-Origin Resource Sharing (CORS), MDN Web Docs.
- Content Security Policy (CSP), MDN Web Docs.