Laravel如何将子域名指向自定义域名?
实现Laravel特定子域名跳转到自定义域名的方法
方法一:Laravel路由层处理
将特定子域名的路由规则放在通配子域名路由之前(Laravel路由按匹配顺序执行),通过重定向实现跳转:
// 优先匹配特定子域名xyz.example.com Route::group(['domain' => 'xyz.example.com'], function() { // 匹配该子域名下所有路径,永久重定向到xyz.com对应地址 Route::any('{all}', function($all) { return redirect()->to('https://xyz.com/' . $all, 301); })->where('all', '.*'); }); // 原有通配子域名路由 Route::group(['domain' => '{subdomain}.example.com'], function($subdomain) { Route::get('new-lead', 'Home@new_lead'); });
301为永久重定向,对SEO友好;若需临时跳转可改为302where('all', '.*')确保子域名下所有页面都能映射到新域名对应路径
方法二:服务器配置层处理(推荐,性能更优)
直接在Web服务器(Nginx/Apache)配置中添加跳转规则,无需经过Laravel解析,效率更高:
Nginx配置示例
# 特定子域名跳转规则 server { listen 80; listen [::]:80; server_name xyz.example.com; return 301 https://xyz.com$request_uri; } # 原有通配子域名站点配置 server { listen 80; listen [::]:80; server_name *.example.com; root /path/to/laravel/public; index index.php; location / { try_files $uri $uri/ /index.php?$query_string; } # PHP处理相关配置... }
Apache配置示例
# 特定子域名跳转 <VirtualHost *:80> ServerName xyz.example.com Redirect permanent / https://xyz.com/ </VirtualHost> # 原有通配子域名站点配置 <VirtualHost *:80> ServerName *.example.com DocumentRoot /path/to/laravel/public # Laravel相关配置... </VirtualHost>
注意事项
- 确保目标域名
xyz.com已正确解析到对应服务器,并配置好SSL证书(若使用HTTPS) - 若选择路由层方案,必须保证特定子域名路由在通配路由之前定义,否则会被通配规则优先匹配
内容的提问来源于stack exchange,提问作者Adeel Javed
相关产品推荐
相关产品推荐

