如何将用户定位到他的前缀域名?
1. 解析域名
在域名管理后台(例如阿里云域名管理后台)解析域名设置里添加一条 主机记录为 *,记录类型为 CNAME 域名,例如:*.yourdomain.com
2. 配置 Nginx
确保你的 Nginx 配置支持子域名。在 Nginx 配置中,通常需要设置 server 块来处理不同的子域名。你可以设置一个通配符子域名以便处理所有用户的子域名请求。
server {
listen 80;
# listen 80 default_server;
# listen 443 ssl http2 default_server;
server_name *.yourdomain.com; # 主要是这一条
root /var/www/your-laravel-app/public;
index index.php index.html index.htm;
# index index.php index.html index.htm default.php default.htm default.html;
# 伪静态
location / {
# try_files $uri $uri/ /index.php?$query_string;
try_files $uri $uri/ /index.php?$is_args$query_string;
}
# 禁止访问的文件或目录
# location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)
# {
# return 404;
# }
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 或者对应的 PHP 版本
fastcgi_index index.php;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
3. 配置 Laravel
在 Laravel 中,你需要设置中间件来处理子域名的重定向。假设每个用户有一个唯一的子域名,你可以在用户登录后进行重定向。
3.1 设置 .env
添加一个子域名的配置到 .env 文件:
SESSION_DOMAIN=yourdomain.com
3.2 创建中间件
生成一个新的中间件来处理重定向:
php artisan make:middleware RedirectToSubdomain
在 app/Http/Middleware/RedirectToSubdomain.php 中,添加逻辑来处理子域名重定向:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectToSubdomain
{
public function handle($request, Closure $next)
{
if (Auth::check()) {
$user = Auth::user();
$subdomain = $user->subdomain; // 假设用户模型有一个 `subdomain` 属性
$host = $request->getHost();
if ($host !== "{$subdomain}.yourdomain.com") {
$url = $request->getScheme() . '://' . $subdomain . '.yourdomain.com' . $request->getRequestUri();
return redirect()->away($url);
}
}
return $next($request);
}
}
3.3 注册中间件
在 app/Http/Kernel.php 中注册你的中间件:
protected $middlewareGroups = [
'web' => [
// 其他中间件...
\App\Http\Middleware\RedirectToSubdomain::class,
],
];
3.4 在用户登录后设置子域名
在登录控制器中,设置用户的子域名(假设你在 users 表中有一个 subdomain 列):
public function authenticated(Request $request, $user)
{
$subdomain = $user->subdomain;
return redirect()->to("http://{$subdomain}.yourdomain.com");
}
4. 确保用户的子域名
确保你的用户模型有一个 subdomain 属性,并且在用户注册时或用户资料更新时,为每个用户设置一个唯一的子域名。
这样,你就可以根据用户登录后的信息将他们重定向到各自的子域名了。
