简体   繁体   English

htaccess基于cookie值重定向

[英]htaccess redirect based on cookie value

I have searched around Google for a while and have not been able to find a solution. 我已经在Google周围搜索了一段时间,但找不到解决方案。

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. 我将存储hasVisited cookie,如果这是错误的,则将其重定向并在欢迎页面上进行设置。

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. 我可以在PHP和jQuery中使用它,但是当它检查是否设置了cookie时,它将首先加载默认页面内容,然后进行重定向。 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 我所需要的是:a-使用htaccess将在重定向之前先停止默认页面加载b-如何执行上述操作

Any help appreciated. 任何帮助表示赞赏。

You need to do cookie checking with PHP and then call header("Location: http://your-url.com/ ") to redirect them 您需要使用PHP进行Cookie检查,然后调用header(“ Location:http: //your-url.com/ ”)来重定向它们

ie

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 请注意,这将影响SEO-Google将仅能检查您放入其中的每个php文件的欢迎页面。您可以添加此内容以允许Google通过检查

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

You don't need to use PHP. 您不需要使用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. 如何维护先前的上下文取决于您对参数使用SEO优化编码还是传统参数编码。 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). 第二个将其限制为php脚本(您也不想重定向welcome.php使用的CSS)。 You also need to store the initial URI just in case the visitor wants to continue with his or her initial request. 您还需要存储初始URI,以防访客想要继续其初始请求。

This approach is simpler than the alternative PHP check -- which would of course need to be added to every script. 这种方法比替代的PHP检查更简单-当然需要将其添加到每个脚本中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM