Last Updated on November 15, 2021 by Amit

HTTP_REFERER header contains URL of the site where the visiter came from. If you came to this site from Google search the domain in the REFERER header will be google.com .
REFERER header contains the full URL string excluding the fregment part which isnt sent to the server.
With mod-rewrite you can manipulate the referer header using %{HTTP_REFERER} variable in RewriteCond directive.
This article shows how you can block access to a specific http referer using mod_rewrite in htaccess file .

Block a specific http referer using RewriteRule in htaccess

I am going to write a sample rule here to block access to example.com domain. You can modify the rule and change the referer domain to whatever domain you want to disallow access to .
The following rule completely blocks example.com . This won’t allow any referer URLs from the example.com domain to your site.

RewriteEngine On
RewriteCond %{HTTP_REFERER} example\.com [NC]
RewriteRule .* - [F]

Explaination :

  • RewriteEngine On tells server to turn on the engine for rewriting URLs. You can remove this line if it’s already present in your htaccess file and put the other two lines just bellow that.
  • RewriteCond %{HTTP_REFERER} example\.com [NC] this creates a condition under which the rule executes . This says “if the refer header is = example.com” . If the condition is met then it sends a green signal to the RewriteRule line that follows it to run and if it’s not met then the rewriting is skipped and the rule is not triggered.
  • RewriteRule .* – [F] rewrites any requested path to F . The F represents a 403 forbidden error. The rule rewrites any request to a 403 error if the condition above it is met.

The RewriteRule posted above in code block blocks the entire example.com referer site meaning that no referer URLs from that domain to your site will be allowed. Clients will get a 403 forbidden error. However if you do not want to block the entire site but a specific URL or page, you can use the following in your htaccess file :

Block a specific referer URL with htaccess

RewriteEngine On
RewriteCond %{HTTP_REFERER} example\.com/thispage\.php [NC]
RewriteRule .* - [F]

This blocks access to a specific referer page example.com/thispage.php while other referer URLs from the domain will keep working normally.

How useful was this post?

Click on a star to rate it!

Average rating 4.7 / 5. Vote count: 14

No votes so far! Be the first to rate this post.