straube/multiple-domain

Allow developers to create complex domain access rules

straube opened this issue · 3 comments

Despite the possibility of setting a base URL for each domain, it may be interesting to allow developers to create complex domain access rules. The behavior should be kept the same as we have today: if the user is accessing a disallowed URL he/she will be redirected to an allowed URL.

A filter is probably the best solution do achieve this:

add_filter('multiple_domain_redirect', function ($url, $domain) {

    // URL verification logic.

    return $url;
}, 10, 2);

I end up using an action instead a filter. It made more sense.

The default logic uses the base URL from the plugin settings, this way:

if (!empty($this->domains[$this->domain])) {
    $base = $this->domains[$this->domain];
    if (!empty($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], $base) !== 0) {
        wp_redirect(home_url($base));
        exit;
    }
}

A developer may create a custom logic adding a new function to multiple_domain_redirect action. There is only one expected param: the current domain.

Here is an example on how to use the action:

function my_custom_redirect($domain)
{
    // Do nothing if the request is using the original domain.
    if ($domain === MULTPLE_DOMAIN_ORIGINAL_DOMAIN) {
        return;
    }
    // If the URI doesn't start with /cool/path, redirect the user to the original domain.
    if (!empty($_SERVER['REQUEST_URI']) && !preg_match('/^\/cool\/path/i', $_SERVER['REQUEST_URI'])) {
        wp_redirect('http://' . MULTPLE_DOMAIN_ORIGINAL_DOMAIN . '/');
        exit;
    }
}

add_action('multiple_domain_redirect', 'my_custom_redirect');

Following the support case in here, I think the plugin needs a way to prevent redirects based on custom logic. Keeping the current action hook, a filter also could be added. In case the filter returns an empty value (null or false), the redirect could be prevented.

Besides creating a custom redirect logic, one can also disable the built-in redirect using a new filter called multiple_domain_disable_redirect. Here's an example on how to use it:

function my_custom_redirect_check($domain) {
    if ($domain === "mydomain.com") {
        return true;
    }
}

add_filter('multiple_domain_disable_redirect', 'my_custom_redirect_check');

When the filter returns true, the redirect will be disabled.