Martti Laine
Martti Laine

Reputation: 12985

Can htaccess prevent all access to unwanted files?

I'm building something that I want to release as an open source project. To make it easier to use I'd like to go without the public-folder approach, where you hide all other files than index.php (and assets) from public_html. Meaning, I'd like to do it like WordPress, where you simply toss the code on a server and it works, in that URL you tossed it in.

Here is the content of my htaccess-file:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
</IfModule>

Does this code really prevent access to other files? For example, is there any way an attacker could access vendor/Acme/Libraries/Foo.php? Based on my tests it does, but that doesn't mean there isn't a way to circumvent it.

Upvotes: 1

Views: 154

Answers (2)

Andrew Schulman
Andrew Schulman

Reputation: 3544

Yes, an attacker can still access your other code files, using only the rule you provided. But:

  1. On a properly configured server, a call to vendor/Acme/Libraries/Foo.php would execute that file, not display its contents. Which might or might not be good enough, and there's still the possibility of a configuration error that would display the source code.

  2. You can block web access to the remaining files by adding Deny directives, for example:

    <Location />
      Order deny,allow
      Deny from all
      <Files index.php>
        Allow from all
      </Files>
    </Location>
    

Upvotes: 0

anubhava
anubhava

Reputation: 785266

Let's look at your rule closely:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Here this rule is saying that if request is NOT for a valid file then rewrite it to /index.php. Which means /index.php will be invoked for any non-file requests but that also means you are allowing direct access to all the files.

btw QSA is useless here and can be removed.

You cited Wordpress here. Which basically uses /index.php for any non-file, non-directory requests thus allowing direct access to any valid file OR directory.

If you really want to block access to all the files and directories then you probably will need this rule:

RewriteRule ^ index.php [L]

but I am not sure if you want to handle direct access to resources like images, js/css files via index.php also.

Upvotes: 2

Related Questions