Securing Your Website with .htaccess
The .htaccess file is a powerful Apache and LiteSpeed configuration file that sits in your website's root directory. It can be used to implement various security measures that protect your site from common attacks.
Accessing Your .htaccess File
- Log in to cPanel and open File Manager.
- Navigate to your
public_htmldirectory. - If you do not see
.htaccess, click Settings in the top right and tick Show Hidden Files. - Right-click the file and select Edit.
Essential Security Rules
Protect wp-config.php (WordPress)
<Files wp-config.php>
Order Allow,Deny
Deny from all
</Files>
This prevents anyone from directly accessing your WordPress configuration file through a browser.
Disable Directory Browsing
Options -Indexes
Without this rule, visitors can see a list of all files in directories that do not have an index file, potentially exposing sensitive files.
Block Access to Sensitive Files
<FilesMatch "^\.(htaccess|htpasswd|ini|log|sh|bak|config)$">
Order Allow,Deny
Deny from all
</FilesMatch>
Prevent Image Hotlinking
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?yourdomain\.co\.uk [NC]
RewriteRule \.(jpg|jpeg|png|gif|svg)$ - [F]
This prevents other websites from embedding your images, which consumes your bandwidth.
Add Security Headers
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"
These headers protect against content type sniffing, clickjacking, cross-site scripting, and referrer leaking.
Important Warnings
- Always back up your .htaccess file before making changes.
- A syntax error in .htaccess will cause a 500 Internal Server Error for your entire site.
- Test your site thoroughly after adding new rules.
- If your site breaks, restore the backup or remove the problematic rule via File Manager.