I'm looking for a generic (host-independent) set of mod_rewrite rules for doing HTTP_REFERER checking on resources. I came up with the following which seemed intuitive, but sadly doesn't work:
RewriteCond %{HTTP_REFERER} !^https?://%{HTTP_HOST}/.*
# RewriteRule .* - [F] # <- or whatever
Apparently you can't have a variable on both sides of the comparison. So, a hack:
RewriteCond %{HTTP_HOST}##%{HTTP_REFERER} !^([^#]*)##https?://\1/.*
But wow, that's ugly -- and if you don't know exactly what's going on, it's terribly confusing.
Is there a better (cleaner) way to write these rules?
"if you don't know exactly what's going on, it's terribly confusing"
First congrats on the workaround. Checking the source, mod_rewrite.c doesn't seem to do any form of variable interpolation, so I can't think of an alternative. As to your "confusing" point, isn't that why we have comments? I've also tidied up your regexp (e.g. the trailing .* is redundant) and used = as a delim to emphasise that you're doing a comparison.
It might look tacky, but your idea is near optimal in terms of runtime.
#
# Is **HTTP_REFERER** of the form http(s)://HTTP_HOST/....
# Note that mod_rewrite only does interpolation in the teststring so this is
# set up in the format AAAA=BBBB and the pattern uses a backreference (\1) to
# match the corresponding elements of AAAA and BBBB
#
RewriteCond %{HTTP_HOST}==%{HTTP_REFERER} !^(.*?)==https?://\1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With