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

Baldie47 picture Baldie47 · Jun 30, 2016 · Viewed 12.7k times · Source

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.

Answer

Joe picture Joe · Jun 30, 2016

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>