skip to Main Content

What is an easy / reliable way to return 404 for an url that looks like this (using .htaccess) ?

/foo/my file name.jpg

I should be able to block more urls in the .htaccess over time, so it is not very easy to url encode them before, file names there can be very long and complex.
A rule / condition that includes quoted file name would be more reliable I think.

I have this and it seems to work but I read that you cannot use 404 with redirect ?!

Redirect 404 "/foo/my file name.jpg"

I could do a RewriteRule to my 404.php, but quoting it like this doesn’t work, how should this be done ?

RewriteRule "/foo/my file name.jpg" 404.php [QSA] 

2

Answers


  1. In a RewriteRule the first arg is a perl compatible regular expression. So try this to match anything with at least one whitespace character

    RewriteRule ^.*?s.*$ 404.php [QSA]
    

    ^ matches the beginning, .*? ungreedily matches zero or more chars, s matches a whitespace char, .* matches zeror or more chars, and $ matches the end. The space char can be the first char, a middle char, or the last char of the file name.

    See https://regex101.com/r/Cznmkp/1

    Login or Signup to reply.
  2. The spaces are probably not the problem with your rule. There are other problems:

    • If your rewrite rule is in .htaccess, it shouldn’t start with a slash. Only rules in /etc/ conf files start with slash. Or make the slash optional (using /?) so that it works in either place.
    • You should use start (^) and end ($) anchors so that your rewrite rule is an exact match, not just a "contains" rule.
    • You should escape the literal period (.) because unescaped, the period is a wildcard in regular expressions.
    • You should use the L flag to say that this rule is the last rule and that subsequent rewrite rules shouldn’t also apply.
    • This rule should go first, before other rules that might conflict with it.
    RewriteRule "^/?foo/my file name.jpg$" 404.php [QSA,L]
    

    If the spaces end up being a problem too, you can escape them with s:

    RewriteRule "^/?foo/mysfilesname.jpg$" 404.php [QSA,L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search