21

I would like .htaccess to perform the following code ONLY if http_referer is from google (.com/ .ru/ .co.uk /.co.in/ etc.). Is this possible?

<filesMatch ".(jpg|jpeg|png|gif)$">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</FilesMatch>
RyanS
  • 627
  • 1
  • 10
  • 26
GameDevGuru
  • 1,095
  • 2
  • 12
  • 27

2 Answers2

33

Well I figured out you can set headers a different way using mod_rewrite making it much easier:

RewriteCond %{HTTP_USER_AGENT} !(googlebot|bingbot|Baiduspider) [NC]  
RewriteCond %{HTTP_REFERER} google [NC]  
RewriteRule ^.*$ - [ENV=LONGCACHE:true]
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate" env=LONGCACHE
Header set Pragma "no-cache" env=LONGCACHE
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT" env=LONGCACHE 
GameDevGuru
  • 1,095
  • 2
  • 12
  • 27
12

Note that you can put the condition in the Header command itself, in ap_expr format (does not require mod_rewrite):

Header set Pragma "no-cache" "expr=%{HTTP_USER_AGENT}=~/(googlebot|bingbot|Baiduspider)/i && %{HTTP_REFERER}=~/google/i"

(not very useful in your particular case since you need to add 3 headers)

rustyx
  • 80,671
  • 25
  • 200
  • 267
  • 1
    Mind you that the `expr` directive is only available in `apache-2.4.10` and later. Some server distributions, such as RedHat Enterprise Linux 7 run `apache-2.4.6` allthough they usually provide an optional higher apache version. https://httpd.apache.org/docs/2.4/mod/mod_headers.html#header – sastorsl Sep 23 '20 at 13:49