1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

1つのLaravelアプリで扱うドメインを追加する方法

Last updated at Posted at 2025-12-15

今使ってるLaravelアプリに、サブドメイン追加したい!といった要望が発生したので、メモ。

前提

Laravel 6系。

1. 環境変数の設定

まずは.envファイルに新しいドメインの設定を追加。

NEW_DOMAIN=new-domain.example.com

で、config/app.phpに環境変数を読み込む設定を追加。
これは他の環境変数の扱い方と一緒。

return [
    // ...既存設定...
    'new_domain' => env('NEW_DOMAIN', 'new-domain.example.com'),
];

2. ルーティングファイル追加

routesに新しいドメイン用のファイルを追加する。
例:routes/new_domain.php

// 新しいドメイン専用のルート定義
Route::get('/', function () {
    return view('new_domain.index');
});

Laravel公式リファレンスではRoute::domain('ドメイン名')で書く方法が例示されているが、個人的にはルーティングファイル分ける方が明確だし綺麗だと思うので好きです。

3. ミドルウェアグループの作成

大体、サブドメイン追加時は、元のドメインとは認証・セッションを分けたい場合が多いと思います。
ので、そんな時は新しいドメイン専用のミドルウェアグループを作成するため、app/Http/Kernel.phpに追記。

protected $middlewareGroups = [
    // ...既存設定...
    'new_domain' => [
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

4. RouteServiceProviderの編集

Laravelはapp/Providers/RouteServiceProvider.phpmapメソッドの記述に従ってルーティングファイルを読みに行くので、先ほど作成したルーティングファイルの設定を記述する。

public function map()
{
    $this->mapApiRoutes();

    $this->mapWebRoutes();

    $this->mapNewDomainRoutes(); // 追加
}

// ...

// 追加
protected function mapNewDomainRoutes()
{
    Route::middleware('new_domain') // 3で作成したミドルウェアグループを指定
        ->domain(config('app.new_domain'))
        ->namespace($this->namespace)
        ->group(base_path('routes/new_domain.php')); // 2で追加したルーティングファイルパスを指定
}

5. 動作確認

以下のコマンドで全ルート一覧を表示し、追加したルートが正しく設定されているか確認。

php artisan route:list

設定されているドメインの確認はtinkerコマンドでも可能

php artisan tinker
>>> config('app.new_domain')

以上!手軽!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?