You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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友好;若需临时跳转可改为302
  • where('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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 21:48:19