PureDevTools

.htaccess Generator

Build Apache .htaccess rules section by section — redirects, HTTPS, security headers, caching, IP blocking, and more

All processing happens in your browser. No data is sent to any server.

Quick Presets

Leave blank to skip

Generated .htaccess
6 lines
# Generated by PureDevTools .htaccess Generator
# https://puredevtools.tools/htaccess-generator

# Disable Directory Listing
Options -Indexes

Copy and place in your web root directory. Requires Apache with AllowOverride All.

Your client’s shared hosting runs Apache and you need to force HTTPS, set up 301 redirects from the old URL structure, enable GZIP compression, add security headers (HSTS, X-Frame-Options, CSP), and block a range of IPs that keep scraping the site. That’s five different .htaccess directives with different syntax — RewriteRule, Header set, mod_deflate, Deny from — and mixing up a RewriteCond flag will silently break your redirects.

Why This Generator (Not Stack Overflow Snippets)

The top .htaccess answers on Stack Overflow are fragmented — one snippet for HTTPS redirect, another for caching, a third for security headers. Copy-pasting them together risks directive conflicts and incorrect ordering (RewriteEngine On must come before rules, security headers need mod_headers enabled). This tool generates a complete, ordered .htaccess file with presets for WordPress, SPA, and PHP apps. Everything runs in your browser; your server configuration never leaves your device.

What Is a .htaccess File?

A .htaccess file (hypertext access) is a directory-level configuration file for Apache web servers. Placed in any directory on your server, it lets you override the main server configuration (httpd.conf) without needing root access. Changes take effect immediately — no server restart required.

Apache reads the .htaccess file on every request for files in that directory and its subdirectories. Common uses include:

URL Redirects: 301 vs 302

The most common .htaccess use case is redirecting URLs. Apache’s Redirect directive handles both types:

# 301 Permanent Redirect — SEO-safe, transfers link equity
Redirect 301 /old-page /new-page

# 302 Temporary Redirect — keeps original URL in search index
Redirect 302 /sale /products

When to use 301: Moving a page permanently (domain migration, URL restructuring, removing www). Search engines will update their index and transfer page authority to the new URL.

When to use 302: Temporary situations — A/B tests, maintenance pages, short-term campaigns. Search engines keep the original URL indexed.

Force HTTPS with .htaccess

The most reliable way to redirect all HTTP traffic to HTTPS is via mod_rewrite:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTPS} off
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

This checks if the HTTPS server variable is off, then redirects to the same URL with https://. The [L,R=301] flags mean Last rule (stop processing) and 301 redirect.

Important: This requires mod_rewrite to be enabled on your server. Most shared hosting providers enable it by default.

Canonical URLs: Force www or Non-www

Serving your site from both example.com and www.example.com creates duplicate content issues for SEO. Force one canonical version:

Force non-www (recommended for most modern sites):

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301]
</IfModule>

Force www:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

Custom Error Pages

Replace Apache’s default error pages with your own branded HTML files:

ErrorDocument 404 /404.html
ErrorDocument 403 /403.html
ErrorDocument 500 /500.html

The path must be relative to your document root. Custom error pages improve user experience and keep visitors on your site when they hit a dead link.

Disable Directory Listing

By default, Apache shows a file listing when a directory has no index.html. This exposes your file structure to visitors — a security and privacy risk:

Options -Indexes

One line is all it takes. With directory listing disabled, Apache returns a 403 Forbidden response instead of showing the file tree.

Block Sensitive File Types

Prevent direct access to sensitive files like environment configurations, database dumps, and backup files:

<FilesMatch "\.(log|env|bak|sql|conf|ini)$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
    Deny from all
  </IfModule>
</FilesMatch>

The <IfModule> blocks ensure compatibility with both Apache 2.4 (mod_authz_core) and older Apache 2.2 syntax.

Common files to block: .env, .log, .bak, .sql, .conf, .ini, .htpasswd, .git

GZIP Compression via mod_deflate

Compress server responses to reduce transfer sizes by 60–80% for text-based resources:

<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE text/html text/plain text/xml
  AddOutputFilterByType DEFLATE text/css application/javascript application/json
  AddOutputFilterByType DEFLATE image/svg+xml application/xml
  AddOutputFilterByType DEFLATE font/woff font/woff2
</IfModule>

Do not compress already-compressed formats like JPEG, PNG, ZIP, or WOFF2 — they gain nothing and the CPU overhead is wasted.

Browser Caching via mod_expires

Tell browsers how long to cache static assets, reducing repeated server requests:

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType image/webp "access plus 1 month"
  ExpiresByType text/css "access plus 1 week"
  ExpiresByType application/javascript "access plus 1 week"
  ExpiresByType font/woff2 "access plus 1 year"
</IfModule>

Cache duration guidelines:

Asset TypeRecommended DurationReason
Images1 monthRarely change; use versioned filenames for cache busting
CSS / JS1 weekChange more often; use content hashes in build tools
Fonts1 yearAlmost never change
HTMLNo cacheAlways fetch fresh for up-to-date content

Security Headers via mod_headers

Security headers tell browsers how to behave when loading your site. They protect against clickjacking, MIME sniffing, XSS attacks, and information leakage:

<IfModule mod_headers.c>
  Header always set X-Frame-Options "SAMEORIGIN"
  Header always set X-Content-Type-Options "nosniff"
  Header always set X-XSS-Protection "1; mode=block"
  Header always set Referrer-Policy "strict-origin-when-cross-origin"
  Header always set Content-Security-Policy "default-src 'self'"
</IfModule>

Header Explanations

X-Frame-Options: Prevents your page from being embedded in an <iframe> on another domain — mitigates clickjacking attacks.

X-Content-Type-Options: nosniff: Prevents browsers from MIME-sniffing a response away from the declared content type. Stops attackers from uploading a .jpg that is really executable JavaScript.

X-XSS-Protection: Legacy header that enables the browser’s built-in XSS auditor (Chrome has removed this; Firefox never implemented it). Included for older browser compatibility.

Referrer-Policy: Controls how much referrer information is included with requests. strict-origin-when-cross-origin sends the full URL for same-origin, but only the origin for cross-origin HTTPS→HTTPS.

Content-Security-Policy: The most powerful security header. default-src 'self' restricts all resources (scripts, styles, images, fonts) to the same origin. Adjust based on your CDN and third-party dependencies.

IP Blocking (Apache 2.4+)

Block specific IP addresses or CIDR ranges from accessing your site:

# Apache 2.4+ syntax
<RequireAll>
  Require all granted
  Require not ip 192.168.1.100
  Require not ip 10.0.0.0/8
</RequireAll>

CIDR notation (e.g. 10.0.0.0/8) lets you block entire IP ranges. The /8 means block all IPs where the first 8 bits match — effectively the entire 10.x.x.x range.

Hotlinking occurs when another website embeds your images directly using your server’s bandwidth without permission. Block it with:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_REFERER} !^$
  RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC]
  RewriteRule \.(jpe?g|png|gif|webp|svg|bmp)$ - [NC,L,F]
</IfModule>

The [F] flag returns 403 Forbidden. Replace the - with an image path to redirect hotlinkers to a “bandwidth theft” image instead.

Apache Module Requirements

Each section in this generator requires specific Apache modules to be enabled:

FeatureRequired Module
Redirects (Redirect directive)mod_alias
Force HTTPS / www redirectsmod_rewrite
Hotlink protectionmod_rewrite
GZIP compressionmod_deflate
Browser cachingmod_expires
Security headersmod_headers
File blockingmod_authz_core (Apache 2.4)
IP blockingmod_authz_core (Apache 2.4)

Most shared hosting providers enable these modules by default. VPS and dedicated server administrators can enable them with a2enmod <module_name> on Ubuntu/Debian.

Does .htaccess Work on nginx?

No. .htaccess is an Apache-specific feature. nginx does not read .htaccess files at all. If you run nginx, you need equivalent directives in your nginx.conf or site configuration.

The CORS Header Generator on this site can export Apache .htaccess format for CORS headers, along with nginx equivalents.

Performance Considerations

.htaccess files add a small overhead to every Apache request because Apache must read them on each file access (unless AllowOverride None is set). For high-traffic sites, consider moving rules to the main httpd.conf or a <VirtualHost> block and disabling .htaccess processing entirely.

For most shared hosting setups, the convenience far outweighs the minimal performance cost.

Related Tools

More DevOps & Networking Tools