php - 用户名作为 laravel 的子域

标签 php .htaccess mod-rewrite laravel laravel-3

我已经设置了一个通配符子域 *.domain.com 并且我正在使用以下 .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 时显示我的用户配置文件。有什么想法可以实现吗?

最佳答案

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

然后在您的 routes.php 文件中使用一个“之前”过滤器,它会在任何其他操作完成之前过滤对您的应用程序的所有请求。

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

关于php - 用户名作为 laravel 的子域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14401468/

相关文章:

php - (PHP) 如何将 crypt() 与 CRYPT_BLOWFISH 一起使用?

php - 这些在php中是什么?例如:$ _ COOKIE [],$ _ POST []等

Php 和 htaccess 错误 - "no input file specified"

php - 具有多个参数的 htaccess 重写规则

php - html 值和准备好的语句

php - 如何更新 Laravel Eloquent 列强制转换为集合

.htaccess 将文件夹重定向到 url

php - Opencart SEF 破坏了相关链接

.htaccess - 将所有 http 流量重定向到 https

php - htaccess RewriteRule url 友好搜索