LoginSignup
1
2

More than 3 years have passed since last update.

GulpのBrowserSyncとPHPのビルトインサーバを組み合わせる

Posted at

要約

コーディングでBrowserSyncを使うときにPHPも使いたいけど、
さくっとビルトインサーバで実行するのに詰まったのでメモ。
要はBrowserSyncのproxyを使うのと、ビルトインサーバを0.0.0.0で実行したらいけた。

ビルトインサーバの起動

localhost:8000でもいいかと思ったけどダメだった。
のでlocalhostじゃなくても参照できるよう起動。

# 先にビルトインサーバ起動。localhostだとproxyが効かない?(効かなかった)
php -S 0.0.0.0:8000

BrowserSyncの方はproxyでビルトインサーバを参照するだけ。

gulpfile.js
// これでlocalhost:3000のリクエストはlocalhost:8000を参照する
browserSync: {
  proxy: 'localhost:8000'
}

その他、htmlファイルでPHPを実行したいのもあったので、細かく調整。
ApacheでいうところのAddTypeに相当する実行をするためにrouter.phpを用意して、

router.php
// .htmlをPHPファイルとして実行する設定
// .htaccess の AddType application/x-httpd-php .html に相当
$path = $_SERVER["SCRIPT_FILENAME"];
if (preg_match("/\.html$/", $path)) {
    chdir(dirname($path));
    return require($path);
}

return false;

ビルトインサーバを下記で起動すればOK

php -S 0.0.0.0:8000 ./router.php

これでfor文とかで項目水増し()も楽チン♪(pugを覚える努力を惜しんだ)

1
2
1

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
2