Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only allow users from specific referrer (redirect the rest) - HTACCESS

I've been trying to block access from everyone that is trying to see a .php page without coming from my specific tracking link.

I want that if they're not coming from my link, they be redirected to another website. I tried using .htaccess method as following:

    RewriteEngine On
RewriteBase /

# allow these referers to passthrough
RewriteCond %{HTTP_REFERER} ^http://subdomain.domain.com
RewriteRule ^ - [L]

# redirect everything else
RewriteRule ^ http://anotherDomain.com/ [R,L]

this is because http://subdomain.domain.com is a tracking url that redirects to website.php but it seems that is not working, and despite any referrer, or even typing the url for website.php directly in toolbar is taking the user to website.php.

what I want to achieve is that only from subdomain.domain.com users can see website.php

thanks in advance.

like image 411
Baldie47 Avatar asked Jun 30 '16 17:06

Baldie47


2 Answers

You can do that using order deny,allow, put this into your .htaccess:

order deny,allow
deny from all
allow from subdomain.domain.com

This will deny everyone access unless they visit via subdomain.domain.com

Then to redirect the users who're not coming from subdomain.domain.com you can use:

RewriteCond %{HTTP_HOST} !^www\.subdomain.domain\.com [NC]
RewriteCond %{HTTP_HOST}   !^$
RewriteRule ^/?(.*)         http://www.example.com/$1 [L,R,NE]

For Apache 2.4:

You can use an IF directive since you're using 2.4:

<If "%{HTTP_HOST} != 'www.subdomain.domain.com'">
Redirect / http://www.example.com/
</If>

and for the order deny,allow add the following around it:

<Limit GET>
</Limit>
like image 157
Joe Avatar answered Nov 17 '22 12:11

Joe


tl;dr

RewriteEngine On
RewriteCond "%{HTTP_REFERER}" "!your-valid-referer.example.com"
RewriteRule ^.*$ - [F]

Details

  • RewriteCond - do a comparison of:
  • "%{HTTP_REFERER}" - the current referer at the time of the request; against:
  • "!your-valid-referer.example.com" - the valid referer; and if it isn't:
  • RewriteRule ^.*$ - no matter what it is;
  • [F] - don't give access to it. Assign an HTTP status code of 403 aka Forbidden.

OP's case

RewriteEngine On
RewriteCond "%{HTTP_REFERER}" "!subdomain.domain.com"
RewriteRule ^ http://anotherDomain.com/ [R,L]
like image 44
Abel Callejo Avatar answered Nov 17 '22 13:11

Abel Callejo