puks1978
puks1978

Reputation: 3697

htaccess redirect based on cookie value

I have searched around Google for a while and have not been able to find a solution.

I need to redirect users of my site to a welcome page only if they havent visited the site before.

I am going to store a hasVisited cookie and redirect if this is false and set it on the welcome page.

I can get this working in PHP and jQuery but when it checks to see if the cookie is set it loads the default page content first and then redirects. Doesnt look too go.

What I am after is: a - Will using htaccess stop the default page loading first before the redirect b - How to do the above

Any help appreciated.

Upvotes: 0

Views: 572

Answers (2)

TerryE
TerryE

Reputation: 10888

You don't need to use PHP. You can simply use a rewrite rule. How you maintain the previous context depends on whether you use SEO optimised encoding or traditional parameter encoding for your parameters. So

RewriteEngine On
RewriteBase   /

RewriteCond   %{HTTP_COOKIE}        !\bhasVisited=       [NC]
RewriteRule   (?:!welcome\.php\b)(?=\.php\b)(.*)  welcome.php?page=$1 [QSA,L]    

The first bit of the rule is to prevent it firing twice. The second limits this to php scripts (you don't want CSS used by welcome.php to be redirected as well). You also need to store the initial URI just in case the visitor wants to continue with his or her initial request.

This approach is simpler than the alternative PHP check -- which would of course need to be added to every script.

Upvotes: 2

Ayub
Ayub

Reputation: 875

You need to do cookie checking with PHP and then call header("Location: http://your-url.com/") to redirect them

i.e.

if (!isset($_COOKIE['hasVisited']) {
    header("Location: http://example.com/welcome.php");
}

Be warned this will effect SEO - Google will only be able to check the welcome page for every php file you put this in. You can add this to allow google through the check

if (!isset($_COOKIE['hasVisited'] && !strpos($_SERVER[‘HTTP_USER_AGENT’],"Googlebot"))

Upvotes: 2

Related Questions