Search code examples
.htaccessmod-rewrite

htaccess rewrite rule for Forbidding urls


I'm not really new to htaccess rewrites, but today I have seen a rule which I've not seen before:

# Access block for folders
RewriteRule _(?:recycler|temp)_/ - [F]

This rule is part of the Typo3 htaccess file.

What does the "?:" mean? Is this some kind of back reference? And what do the underlines stand for? Many thanks!


Solution

  • Rule RewriteRule _(?:recycler|temp)_/ - [F] could be divided into 2 rules for better understanding. like:

    RewriteRule _recycler_/ - [F]
    

    AND

    RewriteRule _temp_/ - [F]
    

    Now let us understand what does that mean:

    • You could see its a shortcut method to make 1 rule out of 2 rules.
    • We could use regex to match multiple patterns and perform same kind of action on URIs which are falling in same criteria(which is matched by regex).
    • In this case we are trying to match _(literal character) followed by (?:recycler|temp). Where ?: stands up for a non-capturing group. So whatever comes into this section(?:.......) will NOT come in backreference capability. Its basically matching string/text recycler OR temp in regex which is preceded and followed by _
    • Now comes what is capturing group: in .htaccess we can use capability of capture matched values which we can use them later eg--> $1 for getting 1st captured value(stored in memory), we could say non-capturing group tells that we want to match a regex but DO NOT store that into memory(because we DO NOT want to use it later onwards into our program).

    Here is an example of capturing group rules in htaccess rules:

    RewriteEngine ON
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1.php -f [NC]
    RewriteRule ^(first|second)/(.*)?$ $1.php?$2 [QSA,NC,L]
    

    Explanation of above example: Its simply makes 2 capturing groups, 1st will have either first OR second, 2nd capturing group will have anything(because of we used .*) in it, so while rewriting part we are using $1 and $2 to get there values. You could clearly see that we could use these values in condition part as well(which becomes in backend like: %{DOCUMENT_ROOT}/first.php OR %{DOCUMENT_ROOT}/second.php).

    Here is an example of non-capturing groups in htaccess Rules:

    RewriteEngine ON
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1.php -f [NC]
    RewriteRule ^(?:first|second)/(third/fourth)/?$ $1.php [QSA,NC,L]
    

    Explanation of above example: We could see that we are matching first OR second in rule side so now value of $1 will be either third OR fourth this time since we used non-capturing group for first/second. So backend condition check will become like: %{DOCUMENT_ROOT}/third.php OR %{DOCUMENT_ROOT/fourth.php