If you would like to restrict access to a WordPress file, or a number of files on your website from being accessed from an external source, you can do so by using .htaccess files if you are running an Apache web server. Restricting access to files with .htaccess is ideal for files which still need to be accessed under the hood by your WordPress but never accessed directly by your website visitors, such as the WordPress configuration file wp-config.php found in the root of your WordPress.
WP White Security Security TIP: This article is about restricting access to files which are only used by your website and that might contain sensitive data, such as wp-config.php. If you would like to protect a file or directory from the public and is not used by your website you should password protect such directory as explained in the htaccess tutorial Password protect WordPress wp-admin directory.
Htacess to restrict access to a single WordPress file
In the .htaccess file example below, we are restricting access to the WordPress wp-config.php file.
<files wp-config.php> order allow,deny deny from all </files>
The .htaccess file in the above example should be uploaded to the same directory where the file resides, in this case in the WordPress root directory. If you would like to restrict access to any other individual file on your website change the file name in the first line and upload the .htaccess file to the directory where the file resides. Keep in mind that if you already have an .htaccess file in that directory, simply add the above directives at the end of the .htaccess file.
Restrict file access to by file type with htaccess
To restrict access to a variety of files which share the same file extension, you can use the syntax of the .htaccess file below. Such .htaccess file should be uploaded to the root of your website to apply file restriction site wide. In the below example, we are restricting access to .htaccess files, .htpasswd files, log files and ini files.
<FilesMatch "\.(htaccess|htpasswd|log|ini)$"> Order Allow,Deny Deny from all </FilesMatch>
If you would like to restrict access to more file extensions than the ones specified above, add the extension to the first line between the brackets next to the ini extension.