Apache 2.4 – Forbidden on Everything Except Scripts in Subfolders

apache-2.4mod-rewrite

I want to forbid everything coming on a specific domain (e.g. example.com) except for some entry points (here, PHP files) located on a specific path (e.g. example.com/subfolder1/subfolder2/script.php).

Here's a snippet of the configuration I used within my virtual host for this particular domain. I still get a 403 for everything.

For context, I'm using Apache 2.4.41 + FPM 7.2

<VirtualHost *:443>
  ServerName example.com
  DocumentRoot /my/path
  <Directory /my/path>
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^/subfolder1/subfolder2$
    RewriteRule . - [F,L]
  </Directory>
</VirtualHost>

Best Answer

RewriteCond %{REQUEST_URI} !^/subfolder1/subfolder2$
RewriteRule . - [F,L]

Because of the end-of-string anchor ($) this only permits /subfolder1/subfolder2 exactly (not /subfolder1/subfolder2/script.php) and blocks everything else. Since /subfolder1/subfolder2 is presumably a physical directory then mod_dir will redirect to append the trailing slash, which will then be blocked by this rule. So yes, it does block everything.

You need to remove the end-of-string anchor ($) from the end of the CondPattern. For example:

RewriteCond %{REQUEST_URI} !^/subfolder1/subfolder2

Although, strictly speaking, to avoid conflict with anything that might simply start with subfolder2 (eg. subfolder2foo.php) then you should use a regex like ^/subfolder1/subfolder2($|/) instead.

Note that if this is the only URL-path you need to allow the you don't need the condition, since the test should be performed in the RewriteRule directive directly. For example:

RewriteRule !^/subfolder1/subfolder2($|/) - [F]

The L flag is not required with the F flag; it is implied.


Alternatively, don't use mod_rewrite at all. For example:

  <Directory /my/path>
    Require all denied
  </Directory>
  <Directory /my/path/subfolder1/subfolder2>
    Require all granted
  </Directory>

This is preferable to mod_rewrite, unless you have other requirements.

Related Topic