I'm using WordPress on an Apache server & would like to use my .htaccess to set a cookie when someone first lands on my site.
If possible I'd set TWO Cookies to:
Ordinarily in PHP, I'd just have:
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');
However we've been noticing issues with caching so I wonder if it's possible to achieve this within my .htaccess instead.
Example URL: www.example.com/?teamname=Chicago+Bulls
you can use something like this. this stores the full URL in a cookie called LandingPageURL .
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:/]
you probably want to use options like HttpOnly and Secure for your cookie
there is also another method to set a cookie in .htaccess that goes like this :
<If "%{HTTP_COOKIE} !^.*LandingPageURL.*$">
    Header edit Set-Cookie ^(.*)$  $1;SameSite=None;Secure;HttpOnly
</If>
if you want to read the cookie with php you can go like this
<?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'] );
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With