It is very obvious and in requirement very frequently that you have to protect some of your website file(s) from direct access. Like you obviously want to disallow your projects .htaccess file from direct access. Similar kind of files are config file, documentation files, robots.txt etc…
Now to protect any file we are generally writing codes in file itself. But there is a way to do the same in a efficient manner and this is writing code in htaccess file.
Paste the below code in your htaccess file and change the FILE-NAME to the file name you want to protect from direct access.
<Files ~ "FILE-NAME"> Order allow,deny Deny from all </Files>
Let us assume you want to restrict your htaccess file from direct access, in this case your code will be as follows:
<Files ~ "^\.htaccess"> Order allow,deny Deny from all </Files>
code for robots.txt file as follows:
<Files ~ "robots\.txt"> Order allow,deny Deny from all </Files>
Again by modifying the same code you can restrict similar kind of files like if you want to restrict all .inc files then below code can do the same:
<Files ~ "\.inc$"> Order allow,deny Deny from all </Files>
If you want to restrict all .js and .css files then write the below code in htaccess file
<Files ~ "(.js|.css)"> Order allow,deny Deny from all </Files>
Happy Restriction 🙂