The .htaccess file is a wonderful tool in tweaking the behavior of your website. This file is designed to allow you to customize your site with behaviors that would normally take access to higher level files on the server. Using the .htaccess file allows you to make these types of changes for your specific domain without interfering with other domains or other user accounts on the server.
This tutorial demonstrates how to use the .htaccess file to restrict access to specific files. The server will maintain the ability to access and read the file for use on your site, but a visitor will be able to access the file and view its contents. The example we will use is the php.ini file. This file has configuration information for the php processes that run on your site. Accessing this file can provide information a malicious person may be able to use to exploit your account. We will demonstrate how to block external access to this file via the .htaccess file.
How to prevent access to specific files with .htaccess
- Log into your cPanel dashboard
- Locate the Files category and click on the File Manager tool icon.
- Next, a popup box will display asking which directory you want to begin. If you are working with the primary domain, simply click the radio button labeled Web Root. For an addon or subdomain, you can select the appropriate document root from the Document Root for: dropdown. Once you select your desired directory, click on the Go button to enter. Be certain to check the box labeled Show Hidden Files (dotfiles) as the .thtaccess file is a hidden file.
- This brings you to the the folder selected. Find the .htaccess file in the right-hand panel and highlight it. Click on the Edit button from the toolbar at the top of the page. Click on the Edit button at the bottom of ther resulting popup to continue to the editor.
- You are now in the file editor for the .htaccess file. Paste the following code at the top of the file to prevent visitors from accessing the file. Note in our example we are preventing access to the php.ini file. You can replace this with any file you like and it can be of any fuiletype (ex: html, jpg, php, etc)
#the following code prevents the display of the php.ini file in a browser:
deny from all
- After pasting the code, click on the Save Changes button in the upper right corner to save the htaccess. You can now try and access the file to ensure the block is in place. Below is an example of how the php.ini file would display before and after the code was added to the .htaccess file.