NGINXを使ってSSL通信でLaravelにアクセスする方法

Windows10で開発時にLaravelをSSL通信(https)したい場合、NGINXを使うと簡単です。

バージョン

  • Laravel - 8.x
  • NGINX - 1.20.1

NGINXのインストールと起動確認

  1. https://nginx.org/en/download.htmlからインストールファイル(zip)をダウンロードする
    (今回はStable versionのWindowsをダウンロード)
  2. ダウンロードしたファイルを任意の場所に解凍する
    例)C:\nginx-1.20.1
  3. フォルダ内のnginx.exeをダブルクリック、またはコマンドプロンプトからnginx.exeを実行する
  4. ブラウザでhttp://localhost/にアクセスする

終了はコマンドプロンプトから次のコマンドを実行します。

nginx.exe -s stop
コマンドプロンプトからnginx.exeを実行している場合は、別のコマンドプロンプトを起動して上記コマンドを実行します。

参考

httpでLaravelにアクセスする

設定ファイルの変更

<nginxインストールフォルダ>\conf\nginx.confを編集します。

http > serverの内容を次のように変更します。

http {
    :
    server {
        listen       80;            # 任意のポート
        server_name  local-server;  # 自身のマシン名やIPアドレス

        root   C:/laravel/sample-project/public;    # Laravelのプロジェクトフォルダ/public

        location / {
            index  index.html index.htm index.php;
            try_files $uri $uri/ /index.php?$query_string;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        location ~ \.php$ {
            try_files $uri /index.php = 404;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    }
}

実行

  1. phpのインストールフォルダで次のコマンドを実行する
    php-cgi.exe -b 127.0.0.1:9000
    
  2. nginx.exeを実行する
  3. ブラウザでhttp://<server_name>:<listen>にアクセスする
    上記の場合だと、http://local-server:80
    (必要に応じて、Laravelで定義したルーティングを指定する)

httpsでLaravelにアクセスする

<nginxインストールフォルダ>\conf\nginx.confを編集します。

# HTTPS serverの箇所を有効にし、次のように変更します。

http {
    :
    # HTTPS server
    #
    server {
        listen       443 ssl;
        server_name  local-server;  # 自身のマシン名やIPアドレス

        ssl_certificate         server-crt.pem; # 自分で用意したファイル
        ssl_certificate_key     server-key.pem; # 自分で用意したファイル

        #ssl_session_cache    shared:SSL:1m;
        #ssl_session_timeout  5m;

        #ssl_ciphers  HIGH:!aNULL:!MD5;
        #ssl_prefer_server_ciphers  on;
        root    C:/laravel/sample-project/public;   # Laravelのプロジェクトフォルダ/public

        location / {
            index  index.html index.htm index.php;
            try_files $uri $uri/ /index.php?$query_string;
        }

        location ~ \.php$ {
            try_files $uri /index.php = 404;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    }
}

実行

  1. phpのインストールフォルダで次のコマンドを実行する
    php-cgi.exe -b 127.0.0.1:9000
    
  2. nginx.exeを実行する
  3. ブラウザでhttps://<server_name>:443にアクセスする
    上記の場合だと、https://local-server:443
    (必要に応じて、Laravelで定義したルーティングを指定する)
このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です