.htaccess Generator preview

.htaccess Generator

Generate Apache .htaccess rules for HTTPS redirects, www canonicalization, GZIP compression, browser caching, custom redirects, hotlink protection, and IP blocking.

Key features

  • One-click HTTPS and WWW redirect rules
  • GZIP compression and browser caching configuration
  • Custom 301/302 redirect rule builder
  • Hotlink protection and IP blocking options

Guide

The .htaccess file is a distributed configuration file for Apache HTTP Server. It controls server behavior on a per-directory basis without requiring access to the main server configuration (httpd.conf or apache2.conf) or a server restart. Web hosting providers that run Apache give users .htaccess access because it allows site-specific configuration in shared hosting environments where users cannot modify the main server config. The file name starts with a dot, making it a hidden file on Unix-based systems. It has no file extension. Place it in your website's root directory to affect the entire site, or in a subdirectory to affect only that directory and its children (subdirectories inherit parent .htaccess rules unless overridden by their own .htaccess file). Apache reads .htaccess files on every request, which means changes take effect immediately but also means there is a measurable performance cost compared to directives in the main config. On high-traffic sites (over 100 requests per second), moving .htaccess rules into the virtual host configuration block in httpd.conf is recommended for performance. Apache must be configured with "AllowOverride All" (or specific directive categories like FileInfo, AuthConfig, Indexes, Limit) in the virtual host or directory block for .htaccess files to work. If AllowOverride is set to None, Apache ignores .htaccess files entirely. Most shared hosting providers set AllowOverride All by default. ## URL Redirection Redirects are the most common use of .htaccess. They send visitors and search engines from one URL to another. Proper redirects preserve SEO equity (link juice), prevent broken links after site restructuring, and ensure users reach the correct content. Incorrect or missing redirects result in 404 errors that frustrate users and waste crawl budget. ### 301 Permanent Redirects A 301 redirect tells browsers and search engines that a page has permanently moved to a new location. Search engines transfer approximately 90 to 99 percent of the original page's ranking equity to the new URL. Use 301 redirects when you change a URL slug, move content to a new domain, restructure your site's URL hierarchy, or consolidate duplicate pages. Simple redirect using the Redirect directive: Redirect 301 /old-page.html /new-page.html The Redirect directive is part of mod_alias, which is loaded by default on most Apache installations. It matches the exact URL path. The destination can be a relative path on the same server or an absolute URL on a different domain. Pattern-based redirect using mod_rewrite: RewriteEngine On RewriteRule ^old-directory/(.*)$ /new-directory/$1 [R=301,L] The [R=301,L] flags mean: R=301 sends a 301 HTTP response code, and L (Last) stops processing further rewrite rules for this request. The $1 backreference captures whatever matched the (.*) group, preserving the rest of the URL path. Domain redirect (entire site migration): RewriteEngine On RewriteCond %{HTTP_HOST} ^(www\.)?oldsite\.com$ [NC] RewriteRule ^(.*)$ https://newsite.com/$1 [R=301,L] The [NC] flag makes the condition case-insensitive. The (www\.)? part matches both www.oldsite.com and oldsite.com. This rule preserves the full URL path during the domain migration, so oldsite.com/blog/post-title redirects to newsite.com/blog/post-title. Redirect with query string preservation: RewriteEngine On RewriteRule ^old-page$ /new-page [R=301,L,QSA] The QSA (Query String Append) flag preserves the original query string. Without it, query parameters are dropped during the redirect. So /old-page?id=123 redirects to /new-page?id=123. ### 302 Temporary Redirects A 302 redirect tells browsers and search engines that the move is temporary. Search engines keep the original URL in their index and do not transfer ranking equity. Use 302 redirects for A/B testing (where you want to send some traffic to a variant without affecting the original page's rankings), temporary maintenance pages, seasonal promotions that will return to the original URL, and geographic redirects based on user location. Redirect 302 /sale /summer-sale-2026 A common mistake is using 302 when you mean 301. If a redirect has been in place for more than a few weeks and you have no plan to revert it, it should be a 301. Google has stated that after enough time, they may treat a 302 like a 301, but relying on this behavior is risky. ### www to non-www (or reverse) Force all traffic to the non-www version (canonical URL normalization): RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC] RewriteRule ^(.*)$ https://example.com/$1 [R=301,L] Force all traffic to the www version: RewriteEngine On RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L] Pick one and apply it consistently. Having both www and non-www versions accessible creates duplicate content issues. Google treats these as separate URLs with separate link equity. Set your preferred version in Google Search Console as well. ## HTTPS Enforcement Forcing HTTPS is critical for security, SEO, and user trust. Google has used HTTPS as a ranking signal since 2014. All major browsers display "Not Secure" warnings on HTTP pages that contain forms or collect any input. RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] This checks if the connection is not HTTPS and redirects to the HTTPS version of the same URL. The %{HTTP_HOST} variable preserves the original hostname, so this rule works regardless of whether your domain uses www. For sites behind a load balancer, reverse proxy, or CDN (like Cloudflare, AWS ELB, or Nginx reverse proxy), the HTTPS variable may always appear as "off" because the proxy terminates SSL and forwards traffic to Apache over HTTP internally. In this case, check the X-Forwarded-Proto header instead: RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L] Combine HTTPS enforcement with www normalization in one rule block to avoid double redirects (HTTP www to HTTPS www to HTTPS non-www). A double redirect wastes time and sends two 301 signals to search engines: RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteRule ^(.*)$ https://example.com/$1 [R=301,L] ## Custom Error Pages Default Apache error pages are plain, unhelpful, and expose server software version information that aids attackers. Custom error pages maintain your site's design, provide useful navigation, and keep visitors on your site after encountering an error. ErrorDocument 404 /errors/404.html ErrorDocument 500 /errors/500.html ErrorDocument 403 /errors/403.html ErrorDocument 410 /errors/410.html The path after ErrorDocument is relative to the document root. Your custom 404 page should include your site navigation, a search box, links to popular pages, and a clear message explaining that the requested page was not found. Include your site's logo and branding so users know they are still on your site. You can also use an absolute URL: ErrorDocument 404 https://example.com/not-found However, this causes a 302 redirect to the error page, which means the browser receives a 302 status code followed by a 200 status code for the error page, not the correct 404 status code. This confuses search engines. The relative path method serves the custom error page content directly with the correct 404 (or 500, 403, etc.) status code. Always use relative paths for error documents. The 410 Gone status code is useful when you intentionally remove content permanently. Unlike 404 (Not Found, which implies the content might exist elsewhere or return), 410 tells search engines to remove the URL from their index more quickly. ## Access Control ### IP-Based Access Restriction Block specific IP addresses (Apache 2.2 syntax): Order allow,deny Allow from all Deny from 192.168.1.100 Deny from 10.0.0.0/8 Allow only specific IPs (useful for staging sites and admin areas): Order deny,allow Deny from all Allow from 203.0.113.50 Allow from 198.51.100.0/24 For Apache 2.4+, the syntax uses the Require directive: Require all denied Require ip 203.0.113.50 Require ip 198.51.100.0/24 To restrict a specific file (like wp-login.php on WordPress): <Files wp-login.php> Require ip 203.0.113.50 </Files> ### Password Protection Protect a directory with HTTP Basic Authentication: AuthType Basic AuthName "Restricted Area" AuthUserFile /home/username/.htpasswd Require valid-user The .htpasswd file stores username:hashed_password pairs. Create it using the htpasswd utility: htpasswd -c /home/username/.htpasswd admin The -c flag creates a new file. Omit -c when adding additional users to an existing file. Place the .htpasswd file outside your web root (document root) so it cannot be downloaded through a browser. The AuthUserFile path must be absolute, not relative. HTTP Basic Authentication sends credentials in base64 encoding (not encrypted). Always use HTTPS when password-protecting directories. Without HTTPS, credentials can be intercepted by anyone monitoring network traffic. ### Hotlink Protection Hotlinking occurs when other websites embed your images, videos, or files directly using your URL, consuming your bandwidth and server resources without providing traffic to your site. Block it: RewriteEngine On RewriteCond %{HTTP_REFERER} !^$ [NC] RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC] RewriteCond %{HTTP_REFERER} !^https?://(www\.)?google\.com [NC] RewriteCond %{HTTP_REFERER} !^https?://(www\.)?bing\.com [NC] RewriteRule \.(jpg|jpeg|png|gif|svg|webp)$ - [F,NC] The first condition allows empty referrers (direct access, bookmarks, and some email clients). The second condition allows requests from your own domain. The additional conditions allow search engine image previews. The rule blocks all other image requests with a 403 Forbidden response. You can replace [F] with a redirect to a placeholder image that says "hotlinking is not allowed." ## Performance Optimization ### Gzip/Deflate Compression Enable compression to reduce transfer sizes by 60 to 80 percent for text-based files: <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/plain text/css AddOutputFilterByType DEFLATE text/javascript application/javascript application/x-javascript AddOutputFilterByType DEFLATE application/json application/ld+json AddOutputFilterByType DEFLATE application/xml text/xml application/rss+xml AddOutputFilterByType DEFLATE image/svg+xml AddOutputFilterByType DEFLATE application/font-woff application/font-woff2 AddOutputFilterByType DEFLATE application/vnd.ms-fontobject </IfModule> The <IfModule> wrapper prevents a 500 error if mod_deflate is not installed or loaded. Do not compress already-compressed files (JPEG, PNG, GIF, ZIP, PDF) because the compression adds CPU overhead without reducing file size. ### Browser Caching Set cache expiration headers to reduce repeat page load times by telling browsers to store static assets locally: <IfModule mod_expires.c> ExpiresActive On ExpiresDefault "access plus 1 month" ExpiresByType text/html "access plus 1 hour" ExpiresByType text/css "access plus 1 year" ExpiresByType application/javascript "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/webp "access plus 1 year" ExpiresByType image/svg+xml "access plus 1 year" ExpiresByType image/x-icon "access plus 1 year" ExpiresByType font/woff2 "access plus 1 year" ExpiresByType font/woff "access plus 1 year" ExpiresByType application/font-woff2 "access plus 1 year" </IfModule> HTML pages get short cache times (1 hour or less) because their content changes frequently. CSS, JavaScript, images, and fonts get long cache times (1 year) because they are typically versioned with cache-busting filenames (style.abc123.css) or query parameters (script.js?v=2.1) in production build systems. When you deploy a new version, the filename changes, and browsers fetch the new file. ### ETags ETags are server-generated identifiers for file versions. On multi-server setups (load-balanced environments), ETags can cause cache invalidation problems because each server generates different ETags for the same file based on the file's inode number, which differs across servers. Disable them and rely on Last-Modified headers and Expires headers instead: Header unset ETag FileETag None ## Security Headers Add HTTP security headers to protect against common web attacks: <IfModule mod_headers.c> Header set X-Content-Type-Options "nosniff" Header set X-Frame-Options "SAMEORIGIN" Header set X-XSS-Protection "1; mode=block" Header set Referrer-Policy "strict-origin-when-cross-origin" Header set Permissions-Policy "camera=(), microphone=(), geolocation=()" Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" </IfModule> X-Content-Type-Options "nosniff" prevents browsers from MIME-sniffing a response away from the declared content type, blocking attacks that disguise malicious scripts as image files. X-Frame-Options "SAMEORIGIN" prevents clickjacking by blocking your site from being embedded in iframes on other domains. Only your own domain can frame your pages. Strict-Transport-Security (HSTS) tells browsers to always use HTTPS for your domain for the specified duration (31536000 seconds equals 1 year). The includeSubDomains directive extends this to all subdomains. The preload directive allows submission to the HSTS preload list maintained by browser vendors, which hard-codes HTTPS enforcement into the browser itself. Only add preload if you are certain all subdomains support HTTPS. Referrer-Policy controls how much referrer information is sent when users navigate away from your site. "strict-origin-when-cross-origin" sends the full URL for same-origin requests but only the origin (domain) for cross-origin requests, and nothing for downgrades from HTTPS to HTTP. Permissions-Policy restricts which browser features your site can use. The example above blocks camera, microphone, and geolocation access. This prevents malicious scripts (from compromised third-party libraries or XSS attacks) from accessing sensitive device features. ## Content-Security-Policy A Content Security Policy (CSP) header controls which sources can load scripts, styles, images, and other resources on your pages. This is the strongest defense against cross-site scripting (XSS) attacks because it blocks unauthorized script execution even if an attacker injects malicious HTML. Header set Content-Security-Policy "default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://api.example.com;" Start with a restrictive policy and loosen it as needed. Test in report-only mode first to identify blocked resources without breaking your site: Header set Content-Security-Policy-Report-Only "default-src 'self'; report-uri /csp-report" The report-uri directive sends JSON reports of policy violations to your specified endpoint, letting you identify resources that need to be whitelisted before enforcing the policy. ## Trailing Slash Consistency Inconsistent trailing slashes create duplicate content (example.com/page and example.com/page/ are treated as different URLs by search engines). Force trailing slashes on directories: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*[^/])$ /$1/ [R=301,L] Or remove trailing slashes: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)/$ /$1 [R=301,L] The !-f condition ("not a file") prevents adding slashes to actual file URLs like /style.css. The !-d condition ("not a directory") prevents removing slashes from actual directory paths. Pick one pattern and apply it site-wide. Most modern web applications and CMS platforms prefer URLs without trailing slashes. ## Common .htaccess Errors and Troubleshooting 500 Internal Server Error: This usually means a syntax error in .htaccess or a directive that requires a module that is not loaded. Apache's error log (usually at /var/log/apache2/error.log on Debian/Ubuntu or /var/log/httpd/error_log on CentOS/RHEL) shows the exact file, line number, and error message. Common causes: a typo in a directive name, a missing closing tag, using mod_rewrite directives without RewriteEngine On, or using Apache 2.2 syntax (Order, Allow, Deny) on Apache 2.4+ (which uses Require directives). Redirect loops ("too many redirects"): If a rewrite rule matches its own output, it creates an infinite redirect cycle. The browser stops after 20 redirects and displays an error. Add conditions to exclude the target URL from matching. For example, when redirecting HTTP to HTTPS, the RewriteCond %{HTTPS} off condition prevents the rule from firing again after the redirect. The [L] flag helps but does not prevent all loops in .htaccess because Apache re-reads .htaccess files after internal subrequests. Adding a RewriteCond that checks for the redirect target explicitly can break stubborn loops. RewriteEngine not working: mod_rewrite must be enabled. On most hosting providers, it is enabled by default. On self-managed servers, enable it with: a2enmod rewrite && systemctl restart apache2 (Debian/Ubuntu) or by uncommenting the LoadModule rewrite_module line in httpd.conf and restarting Apache (CentOS/RHEL). AllowOverride None: If the Apache virtual host or main config sets AllowOverride None for your document root, Apache ignores .htaccess files entirely. Contact your hosting provider or, on self-managed servers, set AllowOverride All in the appropriate <Directory> block and restart Apache. Performance issues: Each .htaccess file is read and parsed on every single HTTP request. If you have .htaccess files in nested directories, Apache reads all of them (from the root down to the requested directory) for every request. Move rules to the main server config when possible for performance-critical sites. This tool generates .htaccess rules based on your selections. Choose from redirect types, HTTPS enforcement, caching rules, compression, security headers, error pages, hotlink protection, and access restrictions. The tool outputs ready-to-use .htaccess content with inline comments explaining each rule, so you understand what every line does before pasting it into your server configuration.

Frequently asked questions

What is .htaccess?

It's a configuration file for Apache web servers that controls redirects, security, and performance settings.

Will this work on my server?

These rules work on Apache servers with mod_rewrite enabled. Nginx and other servers use different configuration formats.

Related guides

Related WebRecast sections