Embed this tool on your site
About this tool
Apache .htaccess is powerful and easy to mistype: a wrong flag or a missing closing tag can return a 500 error for a whole directory. The .htaccess Snippet Generator gives you five ready-made blocks to tick: Force HTTPS (a mod_rewrite 301 redirect), Redirect non-www to www (a 301 to https://www.), Enable gzip compression (mod_deflate for text, JSON, XML and SVG), Set cache headers (mod_expires with one month for CSS and JavaScript and one year for WebP, JPEG and PNG, plus a five-minute Cache-Control on .html files via mod_headers) and a Basic auth placeholder. Selected blocks are merged into one snippet, with repeated lines such as RewriteEngine On written once. There are no input fields, so replace the AuthUserFile path yourself. Paste the result into your .htaccess or VirtualHost config and test it with apachectl configtest.
Why use it
Correct Redirect Syntax: The HTTPS and www blocks use RewriteCond checks with [L,R=301] flags, so you do not have to remember the flag combinations.
Permanent Redirects by Default: Both redirect blocks issue 301s, which search engines treat as a permanent move of the old URL.
Compression in One Tick: The gzip block enables mod_deflate for HTML, CSS, JavaScript, JSON, XML, plain text and SVG inside an IfModule guard.
Static Asset Caching: The cache block sets a one-month expiry for CSS and JavaScript, one year for WebP, JPEG and PNG images, and a five-minute revalidation window for .html files.
Merged, Deduplicated Output: Tick several blocks and get one snippet with shared lines written once, ready to copy.
How to use
- Tick the blocks you need: Force HTTPS, Redirect non-www to www, Enable gzip compression, Set cache headers or Basic auth placeholder. Select all options ticks every block.
- Read the merged snippet, which updates as you tick boxes and writes repeated lines such as RewriteEngine On only once.
- If you used Basic auth placeholder, replace /absolute/path/to/.htpasswd with the real path to your password file and change AuthName if you like.
- If you used Set cache headers, check that the mod_headers block ends with </IfModule> — the current output leaves that closing line out, so add it.
- Click Copy output and paste the snippet into your .htaccess file or Apache VirtualHost block, keeping rewrite rules before other directives.
- Run apachectl configtest (or load a page on shared hosting) to confirm Apache accepts the configuration.
When it helps
- When migrating a site to HTTPS and needing to redirect all HTTP traffic with a 301
- When you want to redirect a bare domain to its www subdomain for one consistent canonical host
- When you need to password-protect a staging or admin directory without deploying full authentication middleware
- When setting up long-lived cache headers for static assets after switching to a hashed asset build pipeline
- When hardening a shared hosting Apache environment that does not allow editing the main server configuration
Examples
01Force HTTPS + non-www to www
InputTicked: Force HTTPS, Redirect non-www to www
Expected resultRewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
InputTicked: Basic auth placeholder
Expected resultAuthType Basic
AuthName "Restricted Area"
AuthUserFile /absolute/path/to/.htpasswd
Require valid-user
InputTicked: Enable gzip compression
Expected result<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain text/html text/css text/javascript application/javascript application/json application/xml image/svg+xml
</IfModule>
Tips
- Always test .htaccess changes on a staging server first — a syntax error in .htaccess returns a 500 Internal Server Error for all requests on the affected directory
- Run apachectl -t or apache2ctl configtest after editing to catch syntax errors before they affect live traffic; on shared hosting, a request to a simple page immediately after saving will surface errors
- Place your most specific RewriteRules before generic catch-all rules, since Apache processes rules from top to bottom and stops at the first [L] match
- Use the RewriteLog directive (Apache 2.2) or LogLevel rewrite:trace3 (Apache 2.4) in development to see exactly which rules are matching and firing for a given request
- Avoid chaining multiple .htaccess files in nested directories for performance-critical paths — Apache reads every .htaccess in the directory tree for each request, and nesting creates cumulative read overhead
Frequently Asked Questions
What is the difference between .htaccess and a VirtualHost block?⌄
A VirtualHost block in the main Apache configuration applies to the entire virtual host and is processed faster because it is read once at server start. An .htaccess file is read on every request and is typically used on shared hosting where you cannot edit the main config.
Do I need mod_rewrite enabled for URL redirects?⌄
Yes. Most redirect and URL manipulation directives require mod_rewrite to be enabled and AllowOverride All set in the directory's VirtualHost or server config. Most shared hosting providers have mod_rewrite enabled by default.
Why should I use R=301 instead of R=302 for permanent redirects?⌄
A 301 tells search engines and browsers that the redirect is permanent, transferring link equity and allowing the destination URL to be cached. A 302 is temporary and does neither — search engines continue to index the old URL, which dilutes ranking signals.
How do I create an .htpasswd file for basic authentication?⌄
Use the htpasswd command-line utility: htpasswd -c /path/to/.htpasswd username. The -c flag creates the file; omit it for subsequent users to append rather than overwrite. Store the .htpasswd file outside the webroot for security.
Can I use .htaccess on Nginx or Caddy?⌄
No. .htaccess is an Apache-specific format and has no equivalent on Nginx or Caddy. Those servers require configuration in their respective formats: Nginx server blocks in nginx.conf and Caddy directives in a Caddyfile. This tool generates Apache-only output.
What does the [L] flag do in a RewriteRule?⌄
The [L] flag (Last) tells Apache to stop processing further RewriteRules in the current pass if this rule matches. Without it, later rules may override or conflict with the matched rule, causing unexpected behavior.
How do I redirect a specific old URL to a new URL?⌄
Use a Redirect directive for simple path changes: Redirect 301 /old-page /new-page. For pattern-based redirects affecting multiple URLs, use RewriteRule with a regex pattern and the [R=301,L] flags.
Is it safe to enable CORS in .htaccess?⌄
It depends on the scope. Adding Access-Control-Allow-Origin: * is safe for public static assets like fonts or JavaScript libraries. For APIs returning user-specific data, always restrict CORS to specific trusted origins rather than using the wildcard.
Is the cache headers block complete?⌄
Not quite. The merge step removes repeated lines, and it currently drops the second </IfModule> that should close the mod_headers block. Add </IfModule> after </FilesMatch> before saving, or Apache will answer with a 500 error.
Glossary
- mod_rewrite
- An Apache module that provides URL rewriting and redirection using regular expression pattern matching. Required for most URL manipulation tasks including canonicalisation, slug rewriting, and redirect rules.
- RewriteRule
- An Apache directive that matches a URL pattern using a regular expression and rewrites or redirects it to a target URL, optionally with flags controlling behavior like permanent redirect status or case-insensitivity.
- RewriteCond
- A conditional directive that precedes a RewriteRule and adds extra match conditions such as checking the HTTP host header, HTTPS status, or request method before the rule fires.
- AllowOverride
- An Apache server configuration directive that controls which .htaccess directives are permitted in a given directory. AllowOverride All is required for most .htaccess functionality but reduces performance versus main config rules.
- mod_expires
- An Apache module that sets Expires and Cache-Control headers on responses based on file type or last-modified date, enabling browser-side caching of static assets to reduce server load and improve repeat-visit performance.
- .htpasswd
- A file containing username and hashed password pairs used by Apache's basic authentication module. Created and managed with the htpasswd command-line utility and referenced by the AuthUserFile directive in .htaccess.
A LITTLE HELP. A LOT DONE.
Good tools.
Great flow.
Your shortcut to the everyday. Create, convert, calculate,
and get back to what you love.
✳
✳
✓ Free to use✓ No sign-up✓ 500+ possibilities