Search code examples
php.htaccesssubdomainslim

htacess subdomain to domain folder invisible with Slim Framework


I come here to ask you on the best practice for this situation. I red some others questions on Slim / rewrite / htaccess, but no success. No problem encountered here, I just don't know if it's a good practice.

So, with Slim Framework 3, I have a main domain www.domain.com, and a subdomain api.domain.com.

When I put in address bar api.domain.com/messages, it call www.domain.com/api/messages with transparency, no redirection.

To achieve this trick, I put this in my index.php file :

if ($_SERVER['HTTP_HOST'] == 'api.domain.com') {
  $_SERVER['REQUEST_URI'] = '/api' . $_SERVER['REQUEST_URI'];
}

It works very well and I don't want to spend time with rewriting rules... But if anybody have a suggestion, I appreciate it !

Thank you for reading !


Solution

  • One way you can do it is to create an api directory in your root directory with an index.php file to handle your api requests. So in your public/index.php file you could add:

    // public/index.php
    chdir(dirname(__DIR__));
    
    require_once 'vendor/autoload.php';
    
    // api domain so include the api routes
    if ($_SERVER['HTTP_HOST'] == "api.domain.com") {
        require 'api/index.php';
        exit;
    }
    
    // --------------------------------------------
    // non api domain
    
    $app = new Slim\App;
    
    $app->get('/',function($request,$response) {
        return $response->write("I'm not the API site!");
    });
    
    $app->run();
    

    And then handle your api routes separately in the api/index.php file:

    // api/index.php
    $app = new Slim\App;
    
    $app->get('/',function($request,$response) {
        return $response->withJson('base api');
    });
    
    $app->group('/game',function() {
    
        $this->get('',function($request,$response) {
            return $response->withJson('Select a game');
        });
    
        $this->get('/space-invaders',function($request,$response) {
            return $response->withJson('Space Invaders API');
        });
    
        $this->get('/pacman',function($request,$response) {
            return $response->withJson('Pac Man API');
        });
    });
    
    $app->run();