UtilityKit

500+ fast, free tools. Most run in your browser only; Image & PDF tools upload files to the backend when you run them.

Htaccess Snippet Generator

Generate common Apache .htaccess snippet blocks and merge selections.

About Htaccess Snippet Generator

Apache .htaccess is powerful and easy to mistype. A missing slash, a wrong flag, or an incorrect RewriteRule pattern can break an entire site or inadvertently expose directory listings to the public. The .htaccess Snippet Generator produces correct, copy-paste-ready Apache directive snippets for the most common configuration tasks — URL redirects, SSL enforcement, www/non-www canonicalisation, basic authentication, directory listing prevention, custom error pages, browser caching headers, CORS rules, and gzip compression. Select the scenario, fill in your domain name, file paths, and any required parameters, and get a snippet ready to paste into your .htaccess or Apache virtualhost config. Each snippet includes explanatory comments so you understand what each directive does rather than treating .htaccess as a black box of cargo-culted rules copied from Stack Overflow answers.

Why use Htaccess Snippet Generator

Correct RewriteRule Syntax Without Memorisation

Apache's RewriteRule syntax with flags like [R=301,L], [NC], and [QSA] is easy to get subtly wrong. The generator produces syntactically correct rules with the right flag combinations for each redirect scenario.

Prevents Accidental Directory Listing Exposure

The most commonly forgotten security setting on Apache servers is Options -Indexes. The generator always includes this directive in directory protection snippets so you never accidentally expose file listings to search engines or attackers.

301 vs 302 Redirect Guidance Built In

Using a 302 temporary redirect when you mean a permanent 301 sends the wrong signal to search engines and prevents browser caching. The generator explains the difference and defaults to 301 for canonical URL changes to protect SEO.

Cache-Control Headers for Performance Optimisation

Setting long-lived cache headers for static assets dramatically improves repeat visitor performance. The generator produces correct mod_expires and mod_headers directives with MIME-type-specific durations for images, CSS, JS, and fonts.

Basic Auth With Clear Password File Path Instructions

Misconfigured basic authentication (wrong path to .htpasswd, missing AuthType directive) leaves directories unlocked while appearing protected. The generator produces complete, working auth blocks with path guidance.

Commented Output Explains Each Directive

Unlike raw snippets pasted from Stack Overflow, the generated output includes explanatory comments above each directive. This means you can understand and maintain the configuration rather than being afraid to touch it.

How to use Htaccess Snippet Generator

  1. Select the type of snippet you need from the category list: redirects, authentication, caching, security headers, or compression
  2. Fill in any required parameters such as the target URL for a redirect, the username for basic auth, or the cache duration in seconds
  3. Review the generated Apache directives with inline comments explaining each line
  4. Copy the snippet and paste it into your existing .htaccess file or Apache VirtualHost configuration block
  5. If combining multiple snippets, place mod_rewrite rules before other directives and check for rule conflicts
  6. Test your configuration with curl or a browser and verify Apache reports no syntax errors with apachectl configtest

When to use Htaccess Snippet Generator

  • When migrating a site to HTTPS and needing to redirect all HTTP traffic with a 301
  • When canonicalising a domain to remove or enforce the www subdomain for SEO consistency
  • 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 a legacy site needs URL slug restructuring and you must preserve old link equity with 301 redirects
  • When hardening a shared hosting Apache environment that does not allow editing the main server configuration

Examples

Force HTTPS + non-www canonical

Input: Scenario: Redirect HTTP to HTTPS and www to non-www, Domain: example.com

Output: RewriteEngine On # Redirect www to non-www RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L] # Force HTTPS RewriteCond %{HTTPS} off RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Password protect /admin directory

Input: Scenario: Basic auth, Directory: /admin, Realm: Admin Area

Output: AuthType Basic AuthName "Admin Area" AuthUserFile /var/www/.htpasswd Require valid-user # Deny directory listing Options -Indexes

Browser caching for static assets

Input: Scenario: Cache-Control headers, Asset types: CSS, JS, images, fonts

Output: <IfModule mod_expires.c> ExpiresActive On ExpiresByType text/css "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" ExpiresByType image/webp "access plus 1 year" ExpiresByType font/woff2 "access plus 1 year" </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.

Explore the category

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.