Gert-Jan Feijens
Gert-Jan Feijens

Reputation: 11

Wordpress rewrite rules not working for linked root domains (does work for subpages)

Current situation I have an wordpress environment that, thanks to custom logic, I use to make single landing pages and push them to separate domains (linked with DNS-records)

For example if is go to 'landing.purplepanda.be/creation' it shows the page on my site with permalink '/purple-panda-get-creative/'. (in this case landing.purplepanda.be is added with DNS-records)

Current situation This works, for all pages. But when I want a landing page to show on the root domain, it doesn't work and is just redirected to my homepage.

For example if I want to map the page '/purple-panda-get-creative/' to the root domain landing.purplepanda.be, it just redirects to my homepage.

Code:

This is how my domain map looks:

<?php $domainMap = array (
  'https://pandapage.web004.creatief.be/amb-lp/' => 'ambholding.be/',
  'https://pandapage.web004.creatief.be/amb-holding-amb-jobes-ugly/' => 'jobes-holding.be/secret-panda',
...
);

This is my function:

function custom_rewrite_rules() {
    include dirname(__FILE__).'/../domainMap.php';
    $current_host = $_SERVER['HTTP_HOST'];
    // Clear existing rules
    remove_rewrite_rules();

    // Loop through the domain map and add new rules
    foreach ($domainMap as $source_url => $target_url) {
        $slug = basename(rtrim($source_url, '/'));

        // Ensure target domain matches current request domain
        if (parse_url('https://' . $target_url, PHP_URL_HOST) === $current_host) {
            $target_path = trim(parse_url('https://' . $target_url, PHP_URL_PATH), '/');

            // Root domain case (example.com → mapped page)
            if ($target_path === '') {
                echo '<div class="message" style="display:none;"> its a root '. 'index.php?pagename=' . $slug . '</div>';
                add_rewrite_rule('^index\.php/?$', 'index.php?pagename=' . $slug, 'top');
            } else {
                // Subpage case (example.com/page → mapped page)
                add_rewrite_rule('^' . $target_path . '/?$', 'index.php?pagename=' . $slug, 'top');
            }
        }
    }

    // Flush rewrite rules to ensure they are updated
    maybe_flush_rewrite_rules();

    // Debugging: Log the current host and domain map
    error_log('Current Host: ' . $current_host);
    error_log('Domain Map: ' . print_r($domainMap, true));
}

The maybe_flush_rewrite_rules(); only flushes the rules when a change is detected in the domainmap file. That part works, because it is working for subpages.

I tried googling the issue, looking into Wordpress docs and ask AI.

Upvotes: 1

Views: 20

Answers (0)

Related Questions