Laravel and Varnish: admin interface with cookies and public pages without cookies -

If you want Laravel to show cached content from Varnish on public pages (so without a cookie), but still want to use a cookie on admin pages, and switch between them, config the following:

Put every admin page on a subdomain:

in routes.php add the following:

Route::group(array('domain' => ''), function()
//admin routes
Route::group(array('domain' => ''), function()
//public routes

Set cookieless session for public pages

in app/config/session.php

  • Set ‘driver’ to ‘array’. The option “array” will not write cookies. This is what we want for the public pages.
  • Set ‘cookie’ to a decent name.

Leave everything else default.

Override the session driver for admin pages.

The Laravel Session is initialized at the very beginning of each webserver request. There’s no point in overwriting the session driver in a controller or in a route filter (as strangely suggested on the github) because the session is already loaded and initialized before the route filter kicks in.

To overwrite the session config, you have to edit bootstrap/start.php

In bootstrap/start.php

Right after this line

require $framework.'/Illuminate/Foundation/start.php';

write a code snippet that looks like this:

if(\Request::server('HTTP_HOST') == ''){
    Config::set('session.driver', 'native');

By doing this we change the session.driver to “native” (so with a cookie) for the admin pages and not on the public pages.

There is one potential pitfall:

On your admin pages, every asset (css, js, image) must be called from the admin subdomain (except assets from other domains or the cloud).

On your public pages, not a single asset (css, js, image) should be called from the admin subdomain. (so don’t use a “” on a page)

Otherwise, if an assets happens to be a 404 and goes through the webserver, it might conflict or create unwanted cookies.

The above example is a stripped down version of my own implementation. You should care for authentication (I use the Sentry2 package for Laravel). With Sentry and the above setup, you also have to put the login page (or certainly the POST-action) on the admin subdomain. Otherwise the login won’t work (because it will try to write an authentication cookie on the public pages, but can’t because of the “array” session driver, so the user will never be able to login).

There might be other ways to accomplish the same result but this setup definatly works.

Rss Comments

One comment

  1. ha.. I had the same problem, cookies are a pain in the ass

    btw you have a funny typo: Lavarel

    #1 ha

Leave a comment