用户名作为laravel上的子域 [英] Username as subdomain on laravel

查看:61
本文介绍了用户名作为laravel上的子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了通配符子域* .domain.com&我正在使用以下.htaccess文件:

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]

一切正常.

我想在laravel中实现此方法.主要是我想在转到username.domain.com时显示我的用户个人资料.有什么想法可以实现吗?

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?

推荐答案

这很容易.首先-不要更改Laravel提供的默认文件中的.htaccess文件.默认情况下,对您域的所有请求都将被路由到您的index.php文件,这正是我们想要的.

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.

然后在routes.php文件中仅使用之前"过滤器,该过滤器会在完成其他任何操作之前过滤对应用程序的所有请求.

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
    }
});

如果您具有国家/地区扩展名(例如domain.com.au或domain.com.eu),则需要更改计数($ server)以检查4,而不是3

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

这篇关于用户名作为laravel上的子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆