Apache .htaccess Generator
Generate Apache .htaccess rules for common server configurations.
About Apache .htaccess Files
The .htaccess file is a powerful Apache configuration file that allows you to control server behavior on a per-directory basis without editing the main server configuration. It's essential for shared hosting environments where you don't have root access.
Common Use Cases
1. URL Redirects
Redirect visitors from old URLs to new ones. Use 301 redirects for permanent moves (SEO-friendly) and 302 redirects for temporary changes.
Redirect 301 /old-page.html https://example.com/new-page.html
Common scenarios:
- Migrating from HTTP to HTTPS
- Changing domain names
- Reorganizing site structure
- Removing duplicate content
2. URL Rewriting
Transform ugly URLs into clean, SEO-friendly ones without changing your file structure.
/product.php?id=123
/product/123
3. Password Protection
Restrict access to directories or files with HTTP Basic Authentication.
Creating .htpasswd file:
htpasswd -c /path/to/.htpasswd username
4. Browser Caching
Improve site performance by telling browsers to cache static assets locally. This reduces server load and speeds up page loads for returning visitors.
| File Type | Recommended Cache Duration |
|---|---|
| Images (JPG, PNG, GIF) | 1 year (31536000 seconds) |
| CSS & JavaScript | 1 month (2592000 seconds) |
| PDFs & Documents | 1 week (604800 seconds) |
| HTML Pages | 1 hour (3600 seconds) or no cache |
5. Gzip Compression
Enable gzip compression to reduce file sizes by 60-80% for text-based content. This dramatically improves page load times, especially on slower connections.
Performance impact:
- Reduces bandwidth usage by 70% on average
- Improves Core Web Vitals scores
- Essential for mobile optimization
- Minimal CPU overhead on modern servers
Best Practices
- Backup before changes: Always keep a copy of your working .htaccess
- Test thoroughly: One typo can cause a 500 Internal Server Error
- Use comments: Document your rules with # comments
- Order matters: Rules are processed top-to-bottom
- Check syntax: Use online validators or test on staging first
- Monitor logs: Check Apache error logs if something breaks
Common Errors
Usually caused by:
- Syntax errors in .htaccess
- Using directives not allowed by AllowOverride
- Missing required Apache modules (mod_rewrite, mod_deflate)
- Incorrect file permissions (should be 644)
Quick Reference
File location:
.htaccess
(in website root directory)
File permissions:
644 (-rw-r--r--)
Enable mod_rewrite:
sudo a2enmod rewrite
Enable mod_deflate:
sudo a2enmod deflate
Restart Apache:
sudo systemctl restart apache2
Rewrite Flags
[L]- Last rule (stop processing)[R=301]- Redirect (301/302)[NC]- No case (case-insensitive)[QSA]- Query string append[F]- Forbidden (403)[G]- Gone (410)