How to protect wp-config.php using htaccess

The wp-config.php file in WordPress is one of the first files loaded each time a page is viewed.

It contains database settings and encryption keys – in the wrong hands these could be used to take control of your website.

The good news is by default this file is adequately secure. Without access to the files on the web server there is no way to read or edit it – and if an attacker had that access it’s already too late.

It’s not until someone starts editing it or configuring the server that there’s a risk of it being exploited.

The contents could be output if there’s invalid PHP and error reporting enabled or the server is configured to handle PHP files as text.

It’s an unlikely situation – but a very simple change could avoid it completely.

The code below will stop all attempts to access the wp-config.php file from the website – e.g. example.com/wp-config.php

It needs to be added to the start of .htaccess on your server, in the main WordPress directory.

Note: this is for Apache servers only. If it doesn’t work it’s likely you do not have an Apache server.

<files wp-config.php>
order allow,deny
deny from all
</files>