使用 htaccess 设置 Cookie
Set Cookie with htaccess
我在 Apache 服务器上使用 WordPress 并且想使用我的 .htaccess 当有人第一次登陆我的网站时设置 cookie。
如果可能的话,我会设置两个 Cookies:
- 存储完整的 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 中实现这一点。
你可以使用像这样的东西。这会将完整的 URL 存储在名为 LandingPageURL 的 cookie 中。
RewriteEngine On
RewriteBase /
// if the cookie "LandingPageURL" is not set
RewriteCond %{HTTP_COOKIE} !^.*LandingPageURL.*$ [NC]
// then set it ...
RewriteRule ^(.*)$ - [co=LandingPageURL::.example.com:2678400:/]
您可能想为您的 cookie 使用 HttpOnly
和 Secure
等选项
还有另一种在 .htaccess 中设置 cookie 的方法,如下所示:
<If "%{HTTP_COOKIE} !^.*LandingPageURL.*$">
Header edit Set-Cookie ^(.*)$ ;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'] );
}
?>
我在 Apache 服务器上使用 WordPress 并且想使用我的 .htaccess 当有人第一次登陆我的网站时设置 cookie。
如果可能的话,我会设置两个 Cookies:
- 存储完整的 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 中实现这一点。
你可以使用像这样的东西。这会将完整的 URL 存储在名为 LandingPageURL 的 cookie 中。
RewriteEngine On
RewriteBase /
// if the cookie "LandingPageURL" is not set
RewriteCond %{HTTP_COOKIE} !^.*LandingPageURL.*$ [NC]
// then set it ...
RewriteRule ^(.*)$ - [co=LandingPageURL::.example.com:2678400:/]
您可能想为您的 cookie 使用 HttpOnly
和 Secure
等选项
还有另一种在 .htaccess 中设置 cookie 的方法,如下所示:
<If "%{HTTP_COOKIE} !^.*LandingPageURL.*$">
Header edit Set-Cookie ^(.*)$ ;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'] );
}
?>