How can I protect a folder with some files from being accessed by htaccess? I'm newbie so take it with grain of salt.

Hey.

If you want to completely deny access to all files in a directory, you can create a .htaccess file containing only

Deny from all

That will block all access to it.

If you just want to block access to some files, you can use a regular expression:

<Files ~ "^.*\.sql$">
 Order deny,allow
 Deny from all
</Files>

This one would block access to all .sql files.

will I be able still to access them in my scripts?
I want to be able to, yet no one can access them on his browser (while he is trying to hack?)

Yes, this only limits access through the HTTP server, so access by server-side scripts will not be affected.

You can also be more specific in who you block.
For instance, this would block access to all PHP files, except for computers on a typical LAN and the localhost:

<Files ~ "^.*\.php$">
    order deny,allow
    deny from all
    allow from 192.168.0
    allow from 127.0.0.1
</Files>

Like say, if you have shared resources that need to be available to the network, but hidden from the outside.

Ok Im about to do the actual job. I want to protect two folders, one is includes and the other is admin. How do I actually do it.
All files in includes starts with inc (like inc.mydb.php) and in admin they begin with admin (like admin.myadmin.php) except for index.php in admin folder.

Also I have folder editor which have my editor. I want to protect it too. So far I have created index.php and added a line to redirect to parent index file and die. Any suggestio/direction is welcomed!

There are several ways to choose from in this situation.

A passive way to deny access to both folders would be to put a .htaccess in the root of the main project and use the RewriteMatch directive. That would allow you to simply redirect anybody who tries to access anything in either of your protected directories to a location of your choosing.

RedirectMatch 301 /(includes|admin)/.* /

That redirects anybody from those directories over to the root of your project.

Or, you could go a more aggressive way and simply deny them access, returning a 403 "Forbidden" error. This is the same thing I posted earlier, which requires a separate .htaccess file into the target directory.

deny from all

That would deny all files in the directory.

If you want it more targeted, like just blocking admin.myadmin.php , you could do:

<Files ~ "^admin\..*\.php$">
    order deny,allow
    deny from all
</Files>

Hope that helps.

That completely solved my problem
Thanks Atli!

Glad I could help ;-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.