klein / klein.php

A fast & flexible router
MIT License
2.67k stars 290 forks source link

Domain Routing #245

Open TheCodemasterZz opened 10 years ago

TheCodemasterZz commented 10 years ago

Do you have any solution for domain based routing like http://myapp.dev and http://another.myapp.dev

Rican7 commented 10 years ago

Domain (and sub-domain) routing is a server software's job, and is therefore not included in Klein. Look to Nginx, Apache, etc to do this for you. :+1:

TheCodemasterZz commented 10 years ago

Thank youfor your answer. But i am looking for a solution which must be done via coding like laravel http://laravel.com/docs/4.2/routing#sub-domain-routing i am lucky, I found a basic solution using Klein package.

daemkl commented 9 years ago

enlighten us please on how to set up klein.php to do subdomain-routing. interested in that as well...

miladrahimi commented 9 years ago

I have a blog.example.com subdomain which point to exmple.com root, so now the Klein must distinct it from main website as Laravel router does, for example $router->get("blog.example.com", function() { ... } );

HighOnMikey commented 9 years ago

You can load routes by checking which host was requested by the client, although I agree with @Rican7 that this is best left to the web server. Here is a very basic example:

<?php

require_once "vendor/autoload.php";

$request = \Klein\Request::createFromGlobals();
$httpHost = $request->server()->get('HTTP_HOST');

$klein = new \Klein\Klein();

if (preg_match('/^somedomain\.com/', $httpHost)) {
    $klein->respond('GET', '/?', function () {
        return "route: root domain detected";
    });
}

if (preg_match('/^highonmikey\.somedomain\.com/', $httpHost)) {
    $klein->respond('GET', '/?', function () {
        return "route: subdomain detected";
    });
}

// You can reuse the request object for dispatch
$klein->dispatch($request);
micheleriva commented 7 years ago

Hi @HighOnMikey, I've tried with your code but I always get 403 error while using Klein as router and managing wildcard subdomains… any ideas? :(

moo-im-a-cow commented 7 years ago

I had some code that did what you want but without wildcards, and after seeing this, i have modified it to work with preg_replace.

the benifits of using this:

here is a link to the gist i created https://gist.github.com/moo-im-a-cow/60b6407872803488c2a6fcb5ffac7dd9#file-index_original-php index.php is the updated version with preg_replace index_original.php is the original version without preg_replace

hope this helps

HighOnMikey commented 7 years ago

You'd need to change the logic around if you want to change action depending on a wildcard subdomain. Spit balling an example here but something like explode()ing the value of $httpHost. Then check the length of the resulting array and if it's greater than 2 there's a subdomain. You could then use the resulting array to check which subdomain is being used. What @moo-im-a-cow did is also another example.