Question

I have the following snippet:

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://%{SERVER_NAME}/
RewriteRule \.(js|css|png|jpg) - [R=404,L]

Simple and should work right? It seems to 404 the listed filetypes if I have referrers enabled on browser. Disabling referrers it then allows the files to be served. I have checked the value of %{SERVER_NAME} and it is www.mydomain.com I've tested this in multiple browsers and under HTTP and HTTPS, all have the same result. I used the below rewrite to check %{SERVER_NAME}'s value:

RewriteRule servername value_is_%{SERVER_NAME} [R=301,L]

The URL I get redirected to is then https://www.mydomain.com/value_is_www.mydomain.com

That being said the snippet should allow a referrer with that value or an empty one. But why is it being triggered? It's been driving me nuts for the past 2 hours, but it's 5am so I could be just crazy =o\ Thank you in advance, and I'm off to bed!

Was it helpful?

Solution

Problem is, you cannot use variables in conditional patterns (well, at least not until Apache 2.4) as the patterns are being precompiled during server startup.

For your particular problem, though, there's a simple workaround that you may use to mimic the condition:

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{SERVER_NAME}%{HTTP_REFERER} !^(.*)https?://\1/
RewriteRule \.(js|css|png|jpg) - [R=404,L]

Yep, that's all. You cannot use variables but sure can use back-references.

Oh ... and btw. Apache 2.4 does ship with expressions that may be used instead of the conditional patterns:

 RewriteCond expr "! %{HTTP_REFERER} -strmatch '*://%{HTTP_HOST}/*'"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top