How to Use .htaccess to Improve Website Security, SEO, and Performance
- Monday, January 26, 2026
The .htaccess file may look small, but it plays a massive role in controlling how your website behaves. From SEO-friendly redirects and performance optimization to advanced security rules, .htaccess gives you server-level control without touching Apache configuration files. This post covers everything you need to get started, including practical examples for security, performance, and SEO.
What is .htaccess?
The .htaccess (Hypertext Access) file is a powerful configuration file used by Apache web servers to control how your website behaves without needing access to the main server configuration.
Using .htaccess, you can Redirect URLs, Improve SEO, Secure sensitive files, Speed up your website, Control error pages, Enable compression and caching. This makes it one of the most important files for web developers, SEO professionals, and website owners.
Where is the .htaccess File Located?
The .htaccess file usually lives in the root directory of your website: /public_html/.htaccess
If it doesn’t exist, you can create one manually. Make sure the file name starts with a dot. No file extension exists. File permissions are set correctly (usually 644)
Redirect HTTP to HTTPS
Google gives priority to HTTPS websites, so it’s important to force secure connections. Implementing this rule not only ensures all traffic uses HTTPS but also prevents duplicate content issues and boosts user trust, which can positively impact your SEO rankings.
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Redirect Non-WWW to WWW (or Vice Versa)
Redirect your non-www domain to the www version of your website. This is important to prevent search engines from indexing both example.com and www.example.com, which can cause duplicate content issues. By redirecting to the canonical version, you ensure that the correct pages are indexed. Simply enter your domain, for example example.com, and it will redirect to www.example.com.
SEO Benefit: Prevents duplicate URLs in search engines and consolidates link equity.
Redirect non-WWW to WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
Redirect WWW to non-WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
301 Redirect File or Directory
When you move a file or directory, it’s important to redirect the old URL to the new one. A 301 redirect a permanent redirect is commonly used for this purpose. It ensures that any SEO value, link equity, or reputation the old page had is transferred to the new page, preserving your site’s search rankings and user experience.
# 301 Redirect Old File
Redirect 301 /old.html /new.html
# 301 Redirect Entire Directory
RedirectMatch 301 /old/(.*) /new//$1
Caching Javascript, CSS, and Images
Caching JavaScript, CSS, and image files allows browsers to store these static assets locally, reducing the need to download them on every page visit. This improves page load times, reduces server load, and provides a smoother experience for returning visitors. Proper caching also contributes to better Core Web Vitals, which can positively impact SEO performance.
# Caching schema
<FilesMatch "\.(jpg|css|js|png|txt|json)$">
Header set Cache-Control "public, proxy-revalidate, max-age=5184000"
</FilesMatch>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 7 days"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
</IfModule>
Password protect file (requires .htpasswd file)
Basic .htaccess authentication is a simple way to protect sections of your website. You’ll also need to generate an .htpasswd file, which stores the usernames and passwords of authorized users. Enter the path to your .htpasswd file in this generator to set up access control.
# Password Protect file
<Files /admin>
AuthName "Restricted Area"
AuthType Basic
AuthUserFile /home/users/.htpasswd
Require valid-user
</Files>
Prevent Hotlinking
Stop other websites from using your images or files on their pages, which can overload your server. You can also choose to show a different image or file to these sites, such as one that communicates your objection to the unauthorized use.
# Stop hotlinking
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?google.com/.*$ [NC]
# The domain that is hotlinking to you.
RewriteRule \.(.jpg|.png|.css)$ https://www.example.com/images/no-hotlinking.jpg[R=302,L]
# Optional. (No hotlinking Image) What to show instead of the intended image.
Custom Error Pages (400, 404, 500, etc)
Default server error pages are generic and unhelpful, offering little guidance to users. Creating a branded 404 page with helpful links and search functionality improves user experience and keeps visitors engaged.
# Custom 403 errors
ErrorDocument 403 /403.html
# Custom 404 errors
ErrorDocument 404 /404.html
# Custom 503 errors
ErrorDocument 503 /503.html
Block or Allow an IP
Deny from 192.168.1.1
Deny from 203.0.113.0
Block bots
Not all bots are beneficial. Malicious or low-value bots can consume bandwidth and increase server load without delivering meaningful traffic. This rule allows you to block a list of known bad bots.
# Block bad bots
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (badbot|crawler|spam) [NC]
RewriteRule .* - [F,L]
Change default directory page
Apache usually looks for index.html when loading a directory. If you prefer a different default file, such as index.php or foo.html, you can set it by adding the following configuration.
# Change default directory page
DirectoryIndex foo.html
Prevent viewing of .htaccess file
Prevents the server from displaying the contents of your .htaccess file. While not critical, it is a good practice to keep internal server information private.
# Prevent viewing of .htaccess file
<Files .htaccess>
order allow,deny
deny from all
</Files>
Prevent Directory Listing
If no index file is present, Apache may display a list of directory contents. Disabling directory indexing prevents this behavior and helps keep internal server information private.
# Prevent directory listings
Options All -Indexes
Enable GZIP Compression (Speed Boost)
Reduces file size and improves page load speed. Faster pages help achieve better Core Web Vitals and stronger SEO results.
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/json
</IfModule>
Common .htaccess Mistakes to Avoid
- Using multiple redirect rules that conflict
- Forgetting to enable mod_rewrite
- Using 302 instead of 301
- Editing without backup
- Syntax errors causing 500 Internal Server Errors
SEO Best Practices for .htaccess
Always test your redirects carefully, stick to a single canonical URL format, enable compression and caching for static assets, avoid redirect chains, and keep your .htaccess rules clean and minimal.
Conclusion
The .htaccess file is a powerful tool for managing your website’s security, performance, and SEO. When configured correctly, it can improve rankings, speed up your site, protect sensitive areas, and enhance the overall user experience without changing server settings. Start with basic rules for redirects, security, and caching, then add more advanced rules as your website grows. Learning these essentials helps you take full control of how your site works.