使用htaccess设置Cookie
我在Apache服务器上使用WordPress,并希望在有人第一次登陆我的网站时使用我的.htaccess设置 cookie。
如果可能,我会将两个Cookie设置为:
- 存储完整的 URL
- 将值存储在 URL 的参数中(例如teamname)
通常在 PHP 中,我只有:
function set_user_cookie() {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if (!isset($_COOKIE['LandingPageURL'])) {
setcookie('LandingPageURL', $url, time()+2678400, "/");
}
}
add_action( 'init', 'set_user_cookie');
然而,我们一直注意到缓存问题,所以我想知道是否可以在我的.htaccess 中实现这一点。
示例网址:www.example.com/?teamname=Chicago+Bulls
回答
你可以使用的东西像这样。这会将完整的 URL 存储在名为 LandingPageURL 的 cookie 中。
RewriteEngine On
RewriteBase /
// if the cookie "LandingPageURL" is not set
RewriteCond %{HTTP_COOKIE} !^.*LandingPageURL.*$ [NC]
// then set it ...
RewriteRule ^(.*)$ - [co=LandingPageURL:$1:.example.com:2678400:/]
你可能想使用类似的选项HttpOnly,并Secure为您的Cookie
还有另一种在 .htaccess 中设置 cookie 的方法,如下所示:
<If "%{HTTP_COOKIE} !^.*LandingPageURL.*$">
Header edit Set-Cookie ^(.*)$ $1;SameSite=None;Secure;HttpOnly
</If>
如果你想用 php 读取 cookie 你可以这样
<?php
if(!isset($_COOKIE['LandingPageURL'])) {
error_log ("Cookie named 'LandingPageURL' is not set in ".__FILE__." #".__LINE__);
} else {
error_log("Cookie 'LandingPageURL' is set in ".__FILE__." #".__LINE__);
error_log("Value of Cookie is: " . $_COOKIE['LandingPageURL'] );
}
?>
- I do not understand the question , you can use the "inspect element" in "firefox", or the "inspect" option in "edge"