【问题标题】:Set Cookie with htaccess使用 htaccess 设置 Cookie
【发布时间】:2021-02-09 11:57:34
【问题描述】:

我在 Apache 服务器上使用 WordPress 并且想在有人第一次登陆时使用我的 .htaccess 设置 cookie我的网站。

如果可能,我会将 两个 Cookie 设置为:

  1. 存储完整的 URL
  2. 将值存储在 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

【问题讨论】:

  • 您的 .htaccess 中有重定向吗?
  • @MaxMuster 我没有重定向。
  • “但是我们已经注意到缓存的问题,所以我想知道是否可以在我的 .htaccess 中实现这一点。” - 浏览器缓存?还是 WordPress 本身的服务器端缓存?用.htaccess 设置它不会对浏览器缓存产生任何影响——如果这就是你所指的。 (?)
  • 查看这篇关于如何在htaccess helponnet.com/2019/05/23/set-cookies-htaccess中使用mod_rewrite设置cookies的文章

标签: php apache .htaccess cookies http-headers


【解决方案1】:

你可以使用类似的东西。这会将完整的 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:/]

您可能希望为您的 cookie 使用像 HttpOnlySecure 这样的选项

还有另一种方法可以在 .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'] );
}
?>

【讨论】:

  • 谢谢。我在哪里可以看到在浏览器中已正确设置?
  • 我没看懂问题,你可以使用“firefox”中的“inspect element”,或者“edge”中的“inspect”选项
  • 在 Chrome 中,我检查了“应用程序”>“Cookies”,但没有看到 Cookies 中列出的 LandingPageURL :(
  • 感谢您的编辑。你知道我如何在我的页面上输出 Cookie 值来确认它的设置是否正确吗?
猜你喜欢
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-03
  • 2014-06-06
相关资源
最近更新 更多