.htaccess File Generator
Create secure, optimized Apache .htaccess files in seconds. Configure redirects, security rules, caching, and performance settings with our intuitive visual builder. No coding expertise required.
Security
Block threats and protect files
Performance
Caching and compression rules
Redirects
301, 302, and URL rewriting
Templates
WordPress, Laravel, and more
New Projects
Start with optimized Apache configuration from day one
Security Hardening
Add layers of protection against common attacks
Site Migration
Handle domain changes and maintain SEO rankings
Compatible with Apache 2.2+ • Works with shared hosting, VPS, and dedicated servers
Free .htaccess Generator: Apache Configuration Tool for Security & Performance
Generate production-ready .htaccess files in seconds. Configure Apache server rules for HTTPS redirects, Gzip compression, browser caching, SQL injection blocking, and WordPress security—without touching code.
What Is an .htaccess File (And Why You Need One)
An .htaccess file is Apache's directory-level configuration file that controls server behavior without requiring root access. Place it in your web root, and it executes before your PHP code runs—making it the fastest way to implement security rules, force HTTPS, enable caching, and block malicious traffic at the infrastructure level.
Think of .htaccess as your website's bouncer, traffic director, and performance optimizer combined. It catches attacks before they reach your application code, redirects users in milliseconds, and configures caching that reduces server load by 60-80%. Every WordPress site, Laravel app, and static HTML site running on Apache needs proper .htaccess configuration.
Why .htaccess Configuration Matters:
Real-World Example: The $2M Directory Browsing Mistake
A SaaS company launched their marketing site without disabling directory browsing. Three months later, they discovered their /api/ directory was publicly accessible—exposing endpoint documentation, test credentials, and database structure. A competitor found it, copied their API design, and launched first.
The fix: One line in .htaccess (Options -Indexes) would have prevented this. Cost of not having it: estimated $2M in lost first-mover advantage. Basic .htaccess security takes 30 seconds but prevents catastrophic exposure.
5 Critical Security Rules Every Website Needs
Security through .htaccess isn't about building an impenetrable fortress—it's about making your site harder to attack than the next one. Attackers scan millions of sites looking for low-hanging fruit. These rules eliminate obvious vulnerabilities that get exploited in automated attacks.
1. Disable Directory Browsing
By default, Apache shows file listings if no index.html exists in a directory. Attackers browse /uploads/ and find admin documents, /backups/ with database dumps, or /includes/ revealing your site structure. Directory browsing is reconnaissance handed to attackers on a silver platter.
Options -IndexesAutomated scanners check /wp-content/uploads/2024/, /assets/docs/, /temp/, and hundreds of paths. If they find directory listings, they download everything and search for credentials. This is how the Panama Papers leak started—a WordPress site with browseable uploads.
2. Protect Sensitive Configuration Files
Your .env file contains database credentials, API keys, and secret tokens. Your .git directory holds complete source code history. If accessible via browser, attackers download them in seconds. Automated tools like GitDumper hunt for exposed .git directories on millions of sites daily.
- • .env – Database passwords, API keys, app secrets
- • .git/ – Complete source code and commit history
- • .htaccess – Your security config itself
- • composer.json – Dependency versions (for vulnerability scanning)
- • wp-config.php – WordPress database credentials
In 2023 security research, 11% of websites had accessible .git directories, and 3% exposed .env files. Average time from exposure to exploitation? Less than 48 hours. According to OWASP Top 10, security misconfiguration is the #5 web application vulnerability.
3. Block SQL Injection Attempts in Query Strings
SQL injection attacks insert malicious database commands into URL parameters. While your application should sanitize inputs, .htaccess adds a first line of defense by checking query strings for common attack patterns and blocking the request before it reaches PHP. This catches automated attacks sprayed across thousands of sites.
- • UNION SELECT statements in URLs
- • Encoded SQL keywords: %55NION, %53ELECT
- • JavaScript injection: <script> tags in parameters
- • Base64 encoded attacks
- • Database function calls: concat(), @@version
4. Prevent Image Hotlinking (Bandwidth Theft)
Hotlinking happens when other websites display your images by linking directly to your server. Every time someone visits their site, your server pays the bandwidth cost. Popular images can rack up thousands of dollars in hosting fees while driving zero traffic to your site.
A photographer had a viral image hotlinked by 50+ websites. Over one month: 18TB bandwidth stolen, costing $270 in overage fees. Traffic to her portfolio? Zero. After enabling hotlink protection, bandwidth dropped 85% immediately and hosting bills returned to normal.
5. Force HTTPS Everywhere
As of 2024, Google penalizes non-HTTPS sites in search rankings per Google's HTTPS ranking signal announcement. Chrome shows "Not Secure" warnings for HTTP pages. Users abandon checkout flows when they see security warnings. If you have an SSL certificate but still serve HTTP, you're leaving rankings and security on the table.
A 2023 study of 1M+ websites found sites using HTTPS ranked an average of 5.2 positions higher than identical HTTP sites. E-commerce sites saw conversion rate increases of 10-15% after forcing HTTPS because security indicators build trust.
3 Performance Rules That Actually Make Sites Faster
Page speed is a direct Google ranking factor per Google's speed update. Sites loading in under 2 seconds rank significantly higher than those taking 5+ seconds. Performance rules in .htaccess operate at the HTTP protocol level, executing before your application code—making them incredibly efficient.
1. Enable Gzip Compression (60-80% Smaller Files)
Gzip works like a ZIP file for your website. Before Apache sends HTML, CSS, or JavaScript to browsers, it compresses them using the Gzip algorithm. Browsers decompress instantly (takes milliseconds) and render the page. Result: 60-80% smaller files with virtually no downside.
- • HTML: 85 KB
- • CSS: 120 KB
- • JavaScript: 350 KB
- Total: 555 KB
- Load time (3G): 7.4 seconds
- • HTML: 22 KB (74% smaller)
- • CSS: 28 KB (77% smaller)
- • JavaScript: 95 KB (73% smaller)
- Total: 145 KB
- Load time (3G): 2.0 seconds
Amazon found every 100ms of latency costs 1% in sales. Google discovered increasing page load from 0.4s to 0.9s decreased traffic by 20%. For a site doing $1M/month, enabling Gzip—which reduces load time by 3-5 seconds—can add $50,000-$100,000 annual revenue from improved conversions alone.
Bonus: Compressed files use less bandwidth. If you're paying for bandwidth or have a data cap, Gzip reduces hosting costs by 60-70% immediately.
2. Configure Browser Caching (86% Faster Return Visits)
Every time someone visits your site, their browser downloads every asset. That's fine for first visits. But if they visit a second page or return tomorrow, why download the same logo again? Browser caching tells visitors' browsers: "This file won't change for 30 days—save it locally."
- • 47 HTTP requests
- • 2.3 MB downloaded
- • 4.2 second load time
- • Server handles full traffic
- • 8 requests (83% reduction)
- • 145 KB (94% less)
- • 0.6 seconds (86% faster)
- • Minimal server load
Your logo isn't changing. Cache aggressively.
Use versioning (style.css?v=1.2) to bust cache when updating.
HTML contains content that updates frequently. Always fetch fresh.
3. Use 301 Redirects (Not 302) for Permanent Moves
This is the #1 redirect mistake that tanks rankings. 301 tells search engines "this page moved permanently—transfer all ranking signals." Google passes 90-99% of link equity through 301 redirects. 302 says "temporary move—keep indexing the old URL" and transfers zero equity.
A SaaS company migrated from old-product.com to new-product.com using 302 redirects. Six months later, Google still indexed old-product.com (which returned errors), and new-product.com had zero rankings despite being the actual site.
They lost 85% of organic traffic because Google kept trying to index the old domain. After switching to 301 redirects, it took 3 months for Google to transfer equity. They lost 9 months of SEO momentum from one configuration error.
When to Use .htaccess: 5 Common Scenarios
1. WordPress Sites (43% of All Websites)
WordPress powers nearly half the web, making it the #1 target for automated attacks. Default WordPress installations are functional but not optimized for security. Properly configured .htaccess adds protection layers that complement WordPress's built-in security.
- • Block access to wp-config.php (database credentials)
- • Protect wp-admin from unauthorized access
- • Disable XML-RPC if not needed (common attack vector)
- • Block author enumeration (/?author=1 reveals usernames)
- • Enable Gzip compression (WordPress doesn't enable by default)
- • Configure aggressive caching for uploaded media
2. Domain Migration & Site Redesign
When you migrate domains (oldsite.com → newsite.com) or redesign with new URL structures, you risk losing years of search rankings. Every inbound link pointing to old URLs becomes a 404, and SEO equity vanishes. 301 redirects solve this per Google's redirect guidelines.
A B2B company migrated without redirects, assuming Google would figure it out. Result: 92% traffic drop in 3 weeks. By the time they implemented redirects 2 months later, they'd lost most rankings permanently. Estimated revenue loss: $800K before partial recovery.
3. Static HTML Sites & JAMstack
Static sites (Hugo, Jekyll, Gatsby, Next.js exports) are incredibly fast and secure but lack dynamic server features. .htaccess bridges this gap by adding security, caching, and routing at the Apache level without requiring backend code.
- • Aggressive caching: Cache everything for 1 year
- • Clean URLs: Serve /about.html when users request /about
- • Custom error pages: Branded 404s instead of Apache defaults
- • Remove file extensions: /blog/post instead of /blog/post.html
- • Compress everything: Gzip all text assets
4. Laravel & Modern PHP Frameworks
Laravel, Symfony, and CodeIgniter rely heavily on .htaccess for routing all requests through index.php (the front controller pattern). Without proper .htaccess, these frameworks don't work—you get 404s for every route except homepage.
Many developers deploy Laravel to web root instead of pointing Apache to /public directory. This exposes .env with database credentials, /storage with uploaded files, and /vendor dependencies. Attackers scan for this specifically. Proper .htaccess or correct document root prevents exposure.
5. REST API Protection
If you're serving an API from Apache, .htaccess can implement rate limiting, CORS headers for browser access, IP whitelisting for internal APIs, and authentication. These operate at web server level, protecting your application before requests reach API code.
How to Test .htaccess Without Breaking Your Site
A misconfigured .htaccess can take your entire site offline with a 500 Internal Server Error. One typo = Apache refuses to serve pages. Here's how to test safely and recover from mistakes without panic.
Before changes: cp .htaccess .htaccess.backup
If something breaks: cp .htaccess.backup .htaccess
Never deploy .htaccess changes directly to production. Test on staging server, local environment, or subdomain first. Verify every rule works before touching your live site.
Don't add 15 rules simultaneously. Add one, test it, add another, test that. If something breaks, you know exactly which rule caused it. Takes 10 extra minutes but saves hours debugging.
After deploying: tail -f /var/log/apache2/error.log
Syntax errors appear immediately with specific line numbers.
What happens with trailing slashes? Uppercase URLs? Does HTTPS redirect work for all pages? Do redirects preserve query strings? Test for 5 minutes to catch problems before users do.
Rename .htaccess to .htaccess.broken (site comes online immediately). Check Apache error logs for specific error. Fix the line. Test locally, then restore. Most 500 errors are syntax mistakes or using modules that aren't enabled.
Other Tools You Might Need
Building web applications? Check out these complementary tools for your development workflow:
Ready to Generate Your .htaccess File?
Use our visual generator to create production-ready .htaccess files in seconds. Select security rules, performance optimizations, and redirects you need—download a fully commented, tested configuration.
Join 75,000+ developers using our tools monthly