Forum Moderators: phranque
I've read posts in this forum that ALMOST do what I'm looking for, but not quite... can you help?
I need a rewriterule in my .htaccess file, that will redirect the user to a specific page in my site, if they are linking to it from one of 3 URLs.
The .htaccess file is in the site root.
So, if anyone links to ANY PAGE on my site from any pages within www.anysite1.com, www.anysite2.com or www.anysite3.com, I want to redirect them to /badpage.php in my site.
I tried this:
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^http://www\.anysite1\.co\.uk [NC]
RewriteRule .* [mysite.com...]
But it seems to continually loop, and never get to my badpage.php page. I assume this is happening as the .htaccess file is in the root, but I want to stop these sites linking to ANY page in my site.
Can you help?
Thanks
The client (browser) will re-request the resource from http://www.example.com/badpage.php, again using the same referrer. Your server's response to this new HTTP request will be another 302 redirect, since /badpage.php will match your rewriterule.
So, the client and server get stuck in a 'infinite' redirection loop.
Another problem is that your code only recognizes the 'www' subdomain of the unwelcome referrers.
A quick fix would be:
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^http://(www\.)?anysite1\.co\.uk [NC]
RewriteRule !^badpage\.php$ http://www.example.com/badpage.php [R=302,L]
Also, there's not much use redirecting things like image, script and CSS resources to a php page, as these either won't be understood by the browser, or will cause rendering errors, possibly defeating your attempt to 'send a message' to these visitors. You can fix that by being more specific about what types of resources should, or should not, be redirected:
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^http://(www\.)?anysite1\.co\.uk [NC]
RewriteCond %{REQUEST_URI} !^/badpage\.php$
RewriteRule ^$¦\.php$¦\.html?$ http://www.example.com/badpage.php [R=302,L]
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^http://(www\.)?anysite1\.co\.uk [NC]
RewriteCond $1 !^badpage\.php$
RewriteCond $1 !\.(gif¦jpe?g¦png¦css¦js)$
RewriteRule (.*) http://www.example.com/badpage.php [R=302,L]
As mentioned here many times, the above code won't work if the client or the visitor's corporate or ISP caching proxy blocks the sending of the HTTP Referer header. However, it's generally effective enough to cause sufficient complaints to the referring Web site to get the link removed.
There are many ways to skin a cat, and these are just two examples of different ways to do it. The code above illustrates several subtleties.
Replace all broken pipe "¦" characters above with solid pipe characters before use; Posting on this forum modifes the pipe characters.
Jim