nginxを使ってローカルにミニマム開発環境を整える

まず表示するファイルを用意します。

mkdir html
echo "OK" > html/index.html

その次に nginx-min.conf というファイルを以下の内容でカレントディレクトリに作成します。

events {
    worker_connections  10;
}

http {
    server {
        listen       8080;
        listen  [::]:8080;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }
    }
}

以下のコマンドで構文チェックします。ファイル名をしている時は絶対パスでないと、nginx標準のディレクトリ配下を見に行って今します。

nginx -t -p `pwd` -c nginx-min.conf

syntax is oktest is successful と表示されていたらOKです。

nginx  -p `pwd` -c nginx-min.conf -g "pid nginx.pid;"

で起動して、停止する時は

kill $(cat nginx.pid)

です。

次にローカル用の証明書を作ります。 https://github.com/FiloSottile/mkcert を使用します。

brew install mkcert

このコマンドでCAをインストールします

mkcert --install

こんなふうに言われます

Created a new local CA 💥
Sudo password:
The local CA is now installed in the system trust store! ⚡️
Warning: "certutil" is not available, so the CA can't be automatically installed in Firefox! ⚠️
Install "certutil" with "brew install nss" and re-run "mkcert -install" 👈

証明書を作成します。

mkcert localhost

ローカルに秘密鍵と、証明書のペアが生成されます。

localhost-key.pem localhost.pem

nginxの設定を以下の様に書き換えて再度、起動します。

events {
    worker_connections  10;
}

http {
    server {
        listen       8080;
        listen  [::]:8080;
        server_name  localhost;

        root   html;
        location / {
            index  index.html index.htm;
        }
    }
    server {
        listen       8081 ssl;
        server_name  localhost;

        ssl_certificate     localhost.pem;
        ssl_certificate_key localhost-key.pem;

        location / {
            root   html;
            index  index.html index.htm;
        }
    }
}

起動すると https://localhost:8081/ のURLで証明書のエラーが出ることもなく接続できるのが確認できると思います。

PHPにプロキシすることを考えます。 以下の様な app.php を用意します。

<?php
phpinfo();

これを以下のコマンドで起動しておき

php -S localhost:8082 app.php

nginxの設定をプロキシするよう変えます。

http {
    ...
    server {
        ...
        location / {
            proxy_pass  http://localhost:8082/;
        }

https://localhost:8081/ を開くとPHPの詳細が確認できると思います。


[追記]

nginxの最新バージョンではlogの出力先が固定されているので -e オプションで出力先を変更する必要がある

nginx -e /dev/null  -p `pwd` -c nginx-min.conf -g "pid nginx.pid;"