TransWikia.com

Wildcard subdomain for posts

Craft CMS Asked on April 13, 2021

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!

2 Answers

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!

Answered by Brandon Kelly on April 13, 2021

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.

Answered by Andrea DeMers on April 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP