36 Useful Apache ‘.htaccess’ Tricks for Security and Performance

The .htaccess file is a powerful configuration file for Apache web servers that allows you to control various aspects of your website, including security, performance, and URL management. Below are 36 useful .htaccess tricks to enhance your website’s security and speed.

Security Enhancements

1. Disable Directory Browsing

Prevent users from viewing directory contents.

Options -Indexes

2. Restrict Access to Specific Files

Block access to sensitive files like .htaccess.env, and configuration files.

<FilesMatch "\.(htaccess|htpasswd|ini|env|log|sh|sql)$">
    Order Allow,Deny
    Deny from all
</FilesMatch>

3. Prevent Hotlinking (Image & Bandwidth Theft)

Stop other sites from embedding your images.

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

4. Block Bad Bots & Scrapers

Block malicious user agents.

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (badbot1|badbot2|harmfulscraper) [NC]
RewriteRule ^.* - [F,L]

5. Force HTTPS (SSL Redirection)

Ensure all traffic uses HTTPS.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

6. Enable HTTP Strict Transport Security (HSTS)

Force browsers to always use HTTPS.

Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"

7. Disable Server Signature

Hide Apache version and server info.

ServerSignature Off

8. Protect Against Clickjacking

Prevent your site from being embedded in iframes.

Header always append X-Frame-Options SAMEORIGIN

9. Enable X-XSS-Protection

Mitigate cross-site scripting (XSS) attacks.

Header set X-XSS-Protection "1; mode=block"

10. Enable Content Security Policy (CSP)

Restrict sources of scripts, styles, and other resources.

Header set Content-Security-Policy "default-src 'self'; script-src 'self' https://trusted.cdn.com;"

11. Disable PHP Execution in Uploads Folder

Prevent malicious PHP file execution.

<Directory /uploads>
    php_flag engine off
</Directory>

12. Block IP Addresses

Deny access to specific IPs.

Deny from 123.45.67.89

13. Limit HTTP Methods

Allow only GET, POST, and HEAD requests.

<LimitExcept GET POST HEAD>
    Deny from all
</LimitExcept>

14. Prevent MIME Sniffing

Stop browsers from guessing content types.

Header set X-Content-Type-Options "nosniff"

15. Disable ETags

Reduce fingerprinting risks.

Header unset ETag
FileETag None

Performance Optimizations

16. Enable Gzip Compression

Reduce file sizes for faster loading.

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css text/javascript application/javascript
</IfModule>

17. Leverage Browser Caching

Set expiry headers for static assets.

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
</IfModule>

18. Enable Keep-Alive

Improve connection reuse.

<IfModule mod_headers.c>
    Header set Connection keep-alive
</IfModule>

19. Disable Image Hotlinking with Redirect

Serve a placeholder if hotlinking is detected.

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ /placeholder.jpg [NC,R,L]

20. Enable Cache-Control Headers

Improve caching for static files.

<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
    Header set Cache-Control "max-age=31536000, public"
</FilesMatch>

21. Remove Trailing Slashes

Avoid duplicate content issues.

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

22. Redirect Non-WWW to WWW (or Vice Versa)

Prevent duplicate content.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]

23. Minify CSS, JS, and HTML

Compress files for faster loading (requires mod_deflate).

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css text/javascript
</IfModule>

24. Disable Unnecessary Redirects

Avoid chain redirects (e.g., http → https → www).

# Combine HTTPS and WWW redirects
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^yourdomain\.com [NC]
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [L,R=301]

25. Optimize SSL/TLS Performance

Enable session caching for faster SSL handshakes.

SSLSessionCache shmcb:/tmp/ssl_scache(512000)
SSLSessionCacheTimeout 300

26. Enable HTTP/2 Support

Improve loading speed (requires HTTPS).

<IfModule mod_http2.c>
    Protocols h2 http/1.1
</IfModule>

27. Disable Unused Modules

Reduce overhead by disabling unnecessary modules in Apache config (not .htaccess).

28. Use Asynchronous Loading for JavaScript

Defer parsing of JS (handled via HTML, but .htaccess can help).

29. Optimize .htaccess Itself

Avoid too many rewrite rules (merge where possible).

30. Enable Early Hints (HTTP/2 & HTTP/3)

Preload critical resources.

Header add Link "</style.css>; rel=preload; as=style"

URL & SEO Improvements

31. Redirect Old URLs to New Ones

Handle moved content gracefully.

Redirect 301 /old-page.html /new-page.html

32. Enable Canonical URLs

Avoid duplicate content issues.

RewriteCond %{HTTP_HOST} ^yourdomain\.com [NC]
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [L,R=301]

33. Remove File Extensions (Clean URLs)

Make URLs user-friendly.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

34. Prevent Trailing Slashes on Files

Avoid duplicate content.

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

35. Force Lowercase URLs

Avoid case sensitivity issues.

RewriteEngine On
RewriteMap lowercase int:tolower
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule (.*) ${lowercase:$1} [R=301,L]

36. Custom Error Pages

Improve user experience with friendly error pages.

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

The .htaccess file is a versatile tool for improving security, performance, and SEO on Apache servers. By implementing these 36 tricks, you can harden your website against attacks, speed up load times, and ensure a better user experience.

Would you like any of these explained in more detail? Let me know in the comments!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top