Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Username as subdomain on laravel

I've set up a wildcard subdomain *.domain.com & i'm using the following .htaccess:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} !www\.
RewriteCond %{HTTP_HOST} (.*)\.domain\.com
RewriteRule .* index.php?username=%1 [L]

Everything works perfectly.

I want to implement this method in laravel. Mainly I want to have my user's profile displayed when you go to username.domain.com. Any ideas on achieving this?

like image 892
Ivanka Todorova Avatar asked Jan 18 '13 14:01

Ivanka Todorova


2 Answers

This is easy. Firstly - do NOT change the .htaccess file from the default provided by Laravel. By default all requests to your domain will be routed to your index.php file which is exactly what we want.

Then in your routes.php file just use a 'before' filter, which filters all requests to your application before anything else is done.

Route::filter('before', function()
{
    // Check if we asked for a user
    $server = explode('.', Request::server('HTTP_HOST'));

    if (count($server) == 3) 
    {
        // We have 3 parts of the domain - therefore a subdomain was requested
        // i.e.  user.domain.com

        // Check if user is valid and has access - i.e. is logged in
        if (Auth::user()->username === $server[0])
        {
            // User is logged in, and has access to this subdomain

            // DO WHATEVER YOU WANT HERE WITH THE USER PROFILE
            echo "your username is ".$server[0];
        }
        else
        {
            // Username is invalid, or user does not have access to this subdomain
            // SHOW ERROR OR WHATEVER YOU WANT
            echo "error - you do not have access to here";
        }

    }
    else
    {
        // Only 2 parts of domain was requested - therefore no subdomain was requested
        // i.e. domain.com

        // Do nothing here - will just route normally - but you could put logic here if you want
    }
});

edit: if you have a country extension (i.e. domain.com.au or domain.com.eu) then you will want to change the count($server) to check for 4, not 3

like image 119
Laurence Avatar answered Oct 08 '22 18:10

Laurence


Laravel 4 has this functionality out of the box:

Route::group(array('domain' => '{account}.myapp.com'), function() {

    Route::get('user/{id}', function($account, $id) {
        // ...
    });

});

Source

like image 41
Martti Laine Avatar answered Oct 08 '22 19:10

Martti Laine