Username as subdomain on laravel

后端 未结 4 1442
滥情空心
滥情空心 2021-01-30 07:47

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

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{HT         


        
4条回答
  •  清歌不尽
    2021-01-30 08:23

    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

提交回复
热议问题