LoginSignup
5
7

More than 3 years have passed since last update.

Laravelのコア1つを、マルチドメイン(サブドメイン)を作ったエックスサーバーで駆動させる

Last updated at Posted at 2020-03-10

概要

筆者以前から実験してみたかったのですが、エックスサーバーのサブドメインで、マルチサイトを作れるCMSを構築したい。
個人的にエックスサーバーが好きなんです。すみません。

使い道は、
・テンプレートタイプのLPやホームページの運用
・通販サイト

そんな感じかなぁと。
私は、単純に日々の業務を合理化したいのが目的です。

設定

config/app.php

config/app.php に記述されている urlは 標準だと.envから設定値を読み取り設定しています。
動的に設定したいので、PHPで記述しておきます。
テンプレートで {{ulr('/xxx')}} を使いたい時など設定しておくと便利かと。
.envのAPP_URLは、使っているドメインでも入れておけば良いかと。使われませんので。

    //'url' => env('APP_URL', 'http://localhost'),
    'url' => empty($_SERVER["HTTPS"]) ? "http://" : "https://" . $_SERVER["HTTP_HOST"],

public_html/{subdomain}/

エックスサーバーでサブドメインを作成すると、ドメインの手前の部分はフォルダでpublic_htmlの直下に作成されてきて、そのフォルダがサブドメインのルートディレクトリになりますよね。

サブドメインのルートに標準で作成されているpublicフォルダのデータをコピーします。
ただ、階層が1つ深く沈むのでindex.phpを少々編集が必要です。
autoload.phpとbootstrap/app.php'の相対パス(../)をそれぞれ1つ増やします。

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylor@laravel.com>
 */

define('LARAVEL_START', microtime(true));

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/

require __DIR__.'/../../vendor/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../../bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);

routes/web.php

ここについては、マニュアル通りに設定してみます。
(公式マニュアル)
https://laravel.com/docs/6.x/routing#route-group-subdomain-routing

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


Route::domain('{subdomain}.yourdomain.com')->group(function () {
    Route::get('/', function ($subdomain) {
    //ビュー渡し
        return view('welcome',['subdomain'=>$subdomain]);
    });
    //コントローラ渡し
    Route::get('/', 'Controller@index');
});
    /**
     * コントローラ渡しの時は、引数がこれで渡ります
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $subdomain)
    {
        return view('welcome', [
            'subdomain'=> $subdomain
        ]);
    }

https://subdomain.yourdomain.com 
所定のURLを開いてみると、welcomeテンプレートには、subdomainの変数が取れるようになります。
あとは、このsubdomainを引数として使って、コントローラやモデルを組んでいけば、
マルチサイトの構築は、いつも通りに作っていけば、できそうですね。
なかなか面白いと思います。
比較的簡単なので興味ある方は一度試してみてわ。
でわでわ。

追記

yourdomainやjpの部分も{}でくくると、サブドメインではなくて、通常ドメインも変数化できました。
マルチドメイン運用も1つのCMSで運用できます。
アイデア次第で他にも設計方法はありますので、運用方法やメンテナンスしやすさにあわせて、実装方法をよく検討する事が肝心です。

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


Route::domain('{subdomain}.{yourdomain}.{com}')->group(function () {
    Route::get('/', function ($subdomain) {
    //ビュー渡し
        return view('welcome',['subdomain'=>$subdomain]);
    });
    //コントローラ渡し
    Route::get('/', 'Controller@index');
});
    /**
     * コントローラで、ドメインの引数を取る例
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $subdomain, $yourdomain , $com)
    {
        //ホスト名を配列で表現しても同じ事
        $hostArry = explode(".", $_SERVER['HTTP_HOST']);

        return view('welcome', [
            'subdomain'=> $subdomain
            'yourdomain'=> $yourdomain
            'com'=> $com
        ]);
    }
5
7
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
5
7