Skip to content

Instantly share code, notes, and snippets.

@croxton
Last active March 20, 2019 19:23
Show Gist options
  • Save croxton/68bf8eaaba776230aed8ec7f5eeaba27 to your computer and use it in GitHub Desktop.
Save croxton/68bf8eaaba776230aed8ec7f5eeaba27 to your computer and use it in GitHub Desktop.
Craft 3 live previews across different root (or sub) domains
<?php
// In general.php define an alias:
'aliases' => [
'@baseUrl' => getenv('CRAFTENV_BASE_URL')
],
// In the CP, set the Base URL for each site to @baseUrl/
// When previewing, the CP will therefore always use the hostname the editor logged into as the base url for the preview
// (that happens with 'new' entries anyway regardless of base url, but existing entries use base url).
// We'll switch Craft to the appropriate site for the live preview request, but without changing the domain.
// So no need to worry about the cookie domain or CORS.
$craft_site = '';
$httpHost = '';
// always make sure your sites only load at known domains
// see: https://expressionengine.com/blog/http-host-and-server-name-security-issues
switch ($_SERVER['HTTP_HOST']) {
case 'red-pill.com' :
$httpHost = $_SERVER['HTTP_HOST'];
$craft_site = 'redpill';
break;
case 'blue-pill.com':
$httpHost = $_SERVER['HTTP_HOST'];
$craft_site = 'bluepill';
break;
}
// is an editor live previewing a site other than the one they logged in to?
if ( isset($_POST['livePreview'])
&& $_POST['livePreview'] === 'true'
&& isset($_POST['action'])
&& isset($_POST['siteId'])
&& isset($_SERVER['REQUEST_METHOD'])
&& $_SERVER['REQUEST_METHOD'] === 'POST') {
switch ( $_POST['siteId']) {
case '1':
$craft_site = 'redpill';
break;
case '2':
$craft_site = 'bluepill';
break;
}
}
if ( ! empty($craft_site)) {
DEFINE('CRAFT_SITE', $craft_site);
}
@croxton
Copy link
Author

croxton commented May 11, 2018

@bwing with the above you can sign in to either domain and view previews for the other site(s) without actually changing the domain. Essentially we are telling Craft to load site 2 at the domain for site 1 (or vice versa). So you only need to be logged in to one site to preview any other site.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment