Odd Forms Behavior Results When Duplicate Server Cookies Created Because of 301 Redirect in HTACCESS File

(Posted 10/21/2010) - It appears that when a PHP session cookie is generated and sent to a client (often because a user form needs to pass information across page boundaries) there is an interaction with htaccess redirection (301, 302) in that one cookie is generated for www.aString.com and another for aString.com -- and while both have the same cookie name, they have different cookie sessionID values.

When a PHP script subsequently attempts to get the value for the named cookie, it may get the wrong sessionID value, with unpredictable results.

I don't pretend to understand the root cause of this particular behavior -- but a solution is to insure that when you do 301 redirection during server processing of a client HTTP Request, you additionally rewrite www.aName.com and aName.com to the same hostname. Failure to pick one and rewrite the other may result in server session cookies being issued for both www.aName.com and for aName.com.

Under ideal circumstances www.aName.com and aName.com would be seen as separate domains; but it appears common for things to get confused when the server requests the client to retrieve the cookie name.

I resolved this session cookie ambiguity by adjusting the .htaccess file in the top level server directory for my account. Now only one session cookie is sent to the client for the target hostname.

The comments below should be sufficient to understand the conditions and associated rewrites. Just replace aName below with your hostname; and replace the project directory (store) with your redirection URI. I chose to remove www; if you want to keep www and remove the abrreviated domain, just revise the rewrite rules accordingly.

Here's the [] flagfield syntax:

  • NC means 'no case,'
  • OR means the conditions are logically or'ed as they apply to the condition or rule that follows.
  • R=301 means return a permanent redirection header to the client.
Options +FollowSymLinks
RewriteEngine on
#
# rewrite www.aName.com/store to aName.com/store
RewriteCond %{HTTP_HOST} ^www\.aName\.com$ [NC]
RewriteCond %{REQUEST_URI} ^/store.*$ [NC]
RewriteRUle ^(.*)$ https://aName.com/$1 [R=301,NC]
#
# rewrite aNAME.com and www.aName.com to aName.com/store
RewriteCond %{HTTP_HOST} ^aName\.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.aName\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/.+$ [NC]
RewriteRule ^.*$ https://aName.com/store [R=301,NC]