2

I want to assign a wildcard domain to every entry from a specific type. For instance:

client.example.com

Where client is the slug of an entry. Is that possible? If yes, how?

Thanks!

0
3

It’s definitely possible. Here’s the gist:

  1. Forget the whole subdomain idea, and start by getting everything working using a URI format like /client/<slug>.
  2. Make all subdomain traffic get routed to the same server/virtual host.
  3. Make Craft think that subdomain requests actually had a URI in the format of /client/<slug>, so it will route the request the way it did in step 1.

How you go about the second step depends on whether you’re on Nginx or Apache.

  • For Nginx, add default_server to the server config’s listen directive:

    server {
        listen 80 default_server;
        // ...
    }
    
  • For Apache, create a _default_ virtual host definition:

    <VirtualHost _default_:*>
        // ...
    </VirtualHost>
    

Exact details depend on your hosting environment so you may need to do some of your own googling here. You’ll likely need to restart the webserver before changes take effect, too.

Once you have all subdomain traffic routing to the same place, add something like this to your index.php file:

<?php

$domainParts = explode('.', $_SERVER['HTTP_HOST']);

if (count($domainParts) === 3)
{
    $slug = $domainParts[0];

    // Fake Craft into thinking the URI was actually /clients/<SLUG>/uri/...

    // Nginx:
    $_REQUEST['REQUEST_URI'] = "/clients/$slug".($_REQUEST['REQUEST_URI'] ?? '');

    // Apache:
    $_GET['p'] = "clients/$slug/".($_GET['p'] ?? '');
}

// ...

With that in place, your client.domain.tld requests should start serving those client entry pages!

1
  • Looking at the date, I assume that this is for Craft 2. Should this also work for Craft 3? I have a Structure and would like the level 1 entries to be available at level-1.example.com and level 2, 3 etc at level-1.example.com/level-2, level-1.example.com/level-2/level-3. Also, I'm using Nitro 2 and don't know how to edit the Nginx config. Thanks! (I would prefer not to use multisite if poss.) Feb 24 at 22:49
1

Craft 3.x and Nitro 2:

In Nitro 2, I added a site alias level-1.example.nitro via nitro alias and at top of index.php I have:

$domainParts = explode('.', $_SERVER['HTTP_HOST']);
$uri = $_SERVER['REQUEST_URI'];

if (count($domainParts) === 3)
{
    $slug = $domainParts[0];
    $_GET['p'] = "$slug/".($_GET['p'] ?? $uri);
}

I can visit level-1.example.nitro and level-1.example.nitro/level-2, level-1.example.nitro/level-2/level-3 with the expected results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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