4

I have a LAMP stack on a VPS where I set up multiple virtual hosts for different (sub)domains:

  • example.com
  • www.example.com
  • dev.example.com

Now, I would like to make sure that PHP session data is isolated, i.e. not shared between these websites. Meaning, for example, if I install WordPress on all 3 websites, a user who logs in on one website should not automatically be logged in as well on the other 2 websites when the user visits them.

How can I accomplish this isolation? From what I understand, the session data is stored in one folder on the system: /var/lib/php/sessions. I would create a separate PHP-FPM pool for each website to prevent websites from accessing each other. But do I additionally need to create different session directories as well to ensure session data isolation (i.e. /var/lib/php/sessions/www, /var/lib/php/sessions/dev etc.)? Or is session data unique to each website/vhost (or rather domain) by default?

2
  • The simplest thing would be to change the session name using session_name ('Unique_Name'); Commented Oct 7, 2022 at 12:40
  • @Rohit - I don't know what you believe this will do. It has nothing to do with session isolation.
    – symcbean
    Commented Oct 9, 2022 at 21:03

1 Answer 1

2

The browser will only return cookies to the domain that served them up unless you explicitly instruct it to return the cookie for subdomains by prefixing it with a '.'

However, by default, PHP will use a single pool for the session data. So a user could (in theory) get a cookie and session id from dev.example.com and (via developer tools or similar) use that session id on the www.example.com site - I believe this is the issue you are trying to pre-empt.

Using separate fpm pools is not a very efficient solution. All this does is provide a placeholder where you can specify paths via php_admin_value() - which you can do already in your webserver config. OTOH the fpm approach would also present the opportunity to run as different UIDs which has some benefit in isolation, but will likely cause you more problems until you some expertise in this.

If I were trying to implement a solution for this, I would either use a custom session handler or an auto prepend script along the lines of....

<?php
// with document root as /var/www/html/$SITENAME/htdocs ...
session_save_path('/var/www/html/' . $_SERVER['HTTP_HOST'] . '/sessions');
ini_set('open_basedir', '/var/www/html/' . $_SERVER['HTTP_HOST']);

Note that on debian derived systems PHP's session garbage collector runs out-of-process as a cron job which need to be updated with the paths in use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.