Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic mod_rewrite referrer check

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?

like image 651
tylerl Avatar asked Sep 13 '11 07:09

tylerl


1 Answers

"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/
like image 187
TerryE Avatar answered Oct 02 '22 16:10

TerryE