How can I edit the .htaccess file to prevent hotlinking to .css, .inc files?

I have my functions in a file called functions.inc on my site. How can I edit the .htaccess file to prevent users from viewing it by going to http://example.com/functions.inc

+4
source share
3 answers
<Files ~ "\.inc$"> Order allow,deny Deny from all </Files> 

Useful if you do not have mod_rewrite installed.

+3
source

I am using mod_rewrite for this. For images, etc. This standard includes:

 RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^https?://myhostname\.com/.*$ [NC] RewriteRule \.(gif|jpe?g|png|js|css)$ - [F] 

You can add "inc" to this list of extensions on the last rule.

But to prevent access to certain types of files, I prefer something like:

 RewriteCond %{THE_REQUEST} ^\w+\ /include/ [OR] RewriteCond %{THE_REQUEST} \.php\ HTTP/ RewriteRule ^.*$ - [R=404,L] 

This does two things:

  • The first rule excludes access to the / include directory from external requests, but you can still include / require them; and
  • The second rule restricts access to file names ending in .php. You can use the same thing for .inc files.

In both cases, Apache will give a 404 error (file not found), which I think is better. As a rule, it’s better to say that something doesn’t exist (that you don’t want people to see it), but didn’t talk about it, but you cannot access it. But this is just a personal opinion.

As for why I restricted .php files from direct access: I use mod_rewrite to create “good” URLs. Instead:

 /account/order.php 

this is:

 /account/order 

There are many reasons for this. Aesthetics is one. SEO is different (if instead of /account/order.php?item=123 you have / account / order / 123).

+2
source

I prefer to hide files rather than just deny access to them. So I prefer the mod_rewrite solution for the response with a 404 status code (since Apache 2.2) as the mentioned cletus. But I would also use backup if mod_rewrite is not available, as Byron said.

So let's combine both:

 <IfModule mod_rewrite.c> RewriteEngine on # .inc files RewriteRule \.inc(/|$) - [L,R=404] # URI paths starting with /include/ RewriteRule ^include/ - [L,R=404] </IfModule> <IfModule !mod_rewrite.c> <Files ~ "\.inc$"> Order allow,deny Deny from all </Files> </IfModule> 
0
source

All Articles