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
In a
RewriteRule
the first arg is a perl compatible regular expression. So try this to match anything with at least one whitespace character^
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
The spaces are probably not the problem with your rule. There are other problems:
.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.^
) and end ($
) anchors so that your rewrite rule is an exact match, not just a "contains" rule..
) because unescaped, the period is a wildcard in regular expressions.L
flag to say that this rule is the last rule and that subsequent rewrite rules shouldn’t also apply.If the spaces end up being a problem too, you can escape them with
s
: