I have my functions in a file called functions.inc in my website. How can I edit the .htaccess file to deny users from viewing it by directly going to http://example.com/functions.inc
views:
555answers:
3I use mod_rewrite for this. For images and so on this is a standard include:
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://myhostname\.com/.*$ [NC]
RewriteRule \.(gif|jpe?g|png|js|css)$ - [F]
You can add "inc" into that extension list on the last rule.
But for preventing access to specific file types 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 filenames 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 find is better. Generally it's better to say something doesn't exist (that you don't want people to see) rather than saying it's there but you can't access it. But that's just personal opinion.
As for why I'd restrict .php files from direct access: I use mod_rewrite to create "nice" URLs. Instead of:
/account/order.php
it's:
/account/order
There are many reasons to do this. Aesthetics is one. SEO is another (if instead of /account/order.php?item=123 you have /account/order/123).
<Files ~ "\.inc$">
Order allow,deny
Deny from all
</Files>
Useful if you don't have mod_rewrite installed.
I prefer to disguise files than just forbidding the access to it. Thus I prefer the mod_rewrite solution to response with a 404 status code (since Apache 2.2) as cletus already mentioned. But I would also use a fallback if mod_rewrite is not available as Byron mentioned.
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>