Score:1

Forbidden on everything except for scripts located on subfolders

gr flag

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>
Score:0
kz flag
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.

gr flag
Thanks a lot ! How can I don't think about your last solution ? so simple :D
kz flag
@alxsbn Since you mentioned "subfolder**s**" it wasn't particularly clear whether the last solution would work outside of your limited example. Although you could always use `<DirectoryMatch>` and a regex if you have multiple subfolders.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.