htaccess from www to non-www bringing variable in session/cookie
.htaccess, cookies, redirect, session-variables
Solution
Since, the environment `%{env}` variables are not behaving consistently across different Apache versions, I suggest setting the cookie with a `RewriteRule` itself using the `[CO]` cookie flag.
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteCond %{HTTP_COOKIE} visitor_id=([^;]+) [NC]
RewriteRule .* $0/vid/%1 [C] # Appends the cookie value to the URL
RewriteRule ^(.*)/vid/(.*)$ http://example.com/$1 [L,R=301,CO=visitor_id:$2:.example.com:14400:/]
Here are the list of changes made to your `.htaccess` file:
`RewriteCond` matches are case-insensitive now (using `[NC]`)
The dots in `%{HTTP_HOST}` condition have been escaped `\.` ( `.` matches any char otherwise)
The first `RewriteRule` appends the visitor id (captured as `%1`) to the URL (captured as `$0`)
The last `RewriteRule` parses the visitor id from the URL (as `$1`) and performs a permanent `[R=301]` redirect to `http://example.com` along with writing a cookie named `visitor_id` using the `[CO]` flag.
The syntax of the cookie rewrite flag is as follows
[CO=NAME:VALUE:DOMAIN:lifetime:path:secure:httponly]
where specifying values for name, value and domain is mandatory. The lifetime defaults to `0` which means the cookie persists for the current browser session only. Path defaults to `/`, secure and httponly to `false`.
The `[CO]` flag used specifies domain as `.example.com` so that the cookie becomes accessible to all the hosts under `example.com` domain. The lifetime is specified as `14400` which is in minutes and so amounts to `10` days.
Problem
.htacces redirects from `www.example.com` to `example.com` (same domain without www.) Returning visitor could have in user-agent a `visitor_id` cookie. I want to bring this value through domains within a cookie or session. I tried this, but the cookie is created for the www domain ``` RewriteCond %{HTTP_HOST} ^www.example.com RewriteCond %{HTTP_COOKIE} visitor_id=([^;]+) RewriteRule .* - [C,env=foo:%1] RewriteRule ^(.*) http://example.com [L,R=301] Header set Set-Cookie "visitor_id=%{foo}e; path=/" env=foo ``` Moreover the environment variable works on localhost (Apache 2.4.2, Win32), but online (Apache 2.2.25, linux) the value in cookie is `"%{foo}e"` instead of expected number. Also tried with `mod_session_cookie` but can't find practical examples. How redirect through domains, bringing `visitor_id` in a cookie or session cookie?