.htaccess – How to match beginig of file name via htaccess


You’ve not stated the “specific directory” in which the .htaccess file and files you are protecting is located? (Although that shouldn’t matter if we rework the rule.)

RewriteCond %{REQUEST_URI} ^cat_([0-9a-zA-Z_]+)\.(pdf|doc|jpg|webp) [NC]
RewriteRule . /index.php [R=302,L]

The REQUEST_URI server variable contains the full URL-path (including the slash prefix), so this would normally need to include the “specific directory”, not just the filename (unless you adjust the regex). You have a start-of-string anchor on the regex (although you have omitted the end-of-string anchor) so this condition (RewriteCond directive) will never match.

Your regex would also fail to match your 3rd and 4th examples because your regex character class ([0-9a-zA-Z_]) omits the special characters $, & and - that are present in these filenames. Although I would surmise you do not need to be so specific and catching cat_<anything>.pdf (for example) would be OK.

However, you do not need a separate condition here. It is easier and more efficient to just use the RewriteRule pattern, which matches relative to the directory that contains the .htaccess file (and excludes the slash prefix), so you do not need to worry about the rest of the URL-path.

I also doubt that you should be redirecting to /index.php. Should this not be simply / (the root directory) and allow the directory index (ie. index.php) to be served by mod_dir? Is that not your canonical URL?

Try the following instead, in the .htaccess file in the directory you are protecting.

RewriteRule ^cat_[^/]+\.(pdf|doc|jpg|webp)$ / [R=302,L]

This regex is perhaps slightly more broad than it needs to be, but that also makes it simpler. ie. [^/] matches anything that is not a / (path separator).

And no need for the <IfModule> wrapper, unless this rule is entirely optional.


However, instead of redirecting to the homepage (which is confusing for users and unnecessary for bots) I would simply block (with a 403 Forbidden) such requests instead. For example:

<FilesMatch "^cat_[^/]+\.(pdf|doc|jpg|webp)$">
    Require all denied
</FilesMatch>



Source link

Leave a Comment