Laravel公式のNginxのconfを解説・設定変更する | アントレプログラマー

Laravel公式のNginxのconfを解説・設定変更する

Laravel

こんにちは、ニキです。

この記事はこんな方におすすめです。

  • Laravelの公式通りにNginxを設定したけど、理解が曖昧。
  • Dockerにも対応させたい。
  • SSL通信できるようにしたい。

今回の記事では、Laravel公式のNginxのconfを解説します。そのあとに補足として、DockerやSSL対応についても説明します。

Takaharu Niki

・Webエンジニア6年目。
・バックエンドを中心に、フロントエンドやDevOps業務も経験。
・現在は、自社サービス企業のテックリードとして従事。

Takaharu Nikiをフォローする

Laravel公式のNginxのconfを解説

これが公式サイトに記載のNginxのconfファイルです。それぞれのディレクティブについて解説していきます。

執筆時のLaravelのバージョンは10です。

server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    root /srv/example.com/public;
 
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
 
    index index.php;
 
    charset utf-8;
 
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
 
    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }
 
    error_page 404 /index.php;
 
    location ~ \\.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }
 
    location ~ /\\.(?!well-known).* {
        deny all;
    }
}

参考 https://laravel.com/docs/10.x/deployment#nginx

listen 80;

listenするポート番号を指定します。この場合は、80番でリッスンします。

listen [::]:80;

IPv6も同様にポート番号を指定できます。この場合は、80番でリッスンします。

server_name example.com;

サーバー名を指定します。この場合は、example.comです。本番用ではドメインを、ローカル環境ではlocalhost を指定します。

root /srv/example.com/public;

ルートディレクトリを指定します。この場合は、/srv ディレクトリにexample.comというプロジェクト名で作成しています。

add_header X-Frame-Options “SAMEORIGIN”;

HTTPレスポンスヘッダーに指定します。この場合は、X-Frame-Optionsの値に”SAMEORIGIN”を設定しています。

X-Frame-Optionsはブラウザーに埋め込みタグ内でページをレンダリングさせるかどうかを指定できます。

他のサイトへの埋め込みを拒否することで、クリックジャッキング対策になります。

The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe>, <embed> or <object>. Sites can use this to avoid click-jacking attacks, by ensuring that their content is not embedded into other sites.

参考 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options

X-Frame-Optionsは以下の値を設定できます。

  • DENY

完全に埋め込みを禁止します。

  • SAMEORIGIN

同一オリジンのみ許可します。

DENY The page cannot be displayed in a frame, regardless of the site attempting to do so. SAMEORIGIN The page can only be displayed if all ancestor frames are same origin to the page itself.

参考 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options#directives

add_header X-Content-Type-Options “nosniff”;

HTTPレスポンスヘッダーに指定します。この場合は、X-Content-Type-Optionsの値に”nosniff”を設定しています。

X-Content-Type-Optionsは、MIMEタイプを変更可能かを指定します。これにより悪意のあるMIMEタイプスニッフィングを防ぎます。

The X-Content-Type-Options response HTTP header is a marker used by the server to indicate that the MIME types advertised in the Content-Type headers should be followed and not be changed. The header allows you to avoid MIME type sniffing by saying that the MIME types are deliberately configured.

参考 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options

index index.php;

indexファイルを指定します。この場合は、index.phpを指定しています。

http://example.com/のようにディレクトリをリクエストされた場合にhttp://example.com/index.phpへのリクエストと同様の動きをします。

charset utf-8;

HTTPレスポンスの文字エンコーディングを指定します。この場合は、UTF-8に設定します。

location /

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

URIと比較するプレフィックスを指定します。ここでは”/”を設定しています。

“/”にはすべてのURIがマッチします。

try_files

左から順にファイルの存在をチェックします。

$uriが/(http://localhost)の場合

  • $url

/srv/example.com/public/の中に/というファイルを探します。

  • $url/

/srv/example.com/public/の中に/というディレクトリを探します。

  • /index.php?$query_string

/srv/example.com/public/index.php?$query_stringを探します。

$uriがfoo(http://localhost/foo)の場合

  • $url

/srv/example.com/public/の中にfooというファイルを探します。

  • $url/

/srv/example.com/public/の中にfooというディレクトリを探します。

  • /index.php?$query_string

/srv/example.com/public/index.php?$query_stringを探します。

location =

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

“=”修飾子を使えば、URIとlocationの完全一致を定義できます。この場合は、/favicon.icoや/robots.txtを指定しています。

完全一致が見つかると、検索は終了します。頻発するURIに対して定義すると、リクエストの処理が速くなります。

/favicon.icoや/robots.txtはブラウザやクローラーから頻繁にリクエストされるので、定義の対象として最適です。

Also, using the “=” modifier it is possible to define an exact match of URI and location. If an exact match is found, the search terminates. For example, if a “/” request happens frequently, defining “location = /” will speed up the processing of these requests, as search terminates right after the first comparison. Such a location cannot obviously contain nested locations.

参考 https://nginx.org/en/docs/http/ngx_http_core_module.html#location

access_log off;

アクセスログをoffにします。/favicon.icoや/robots.txtはログとして記録する必要はないでしょう。

log_not_found off;

見つからなかった場合にエラーログへの記録をオフにしています。/favicon.icoや/robots.txtが見つからなくてもログとして記録する必要はないでしょう。

error_page 404 /index.php;

指定のエラーコードに対するエラーページのURIを設定します。ここでは、404エラーが発生した場合に、/index.phpを使用して処理します。

location ~ \.php$

location ~ \\.php$ {
    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    include fastcgi_params;
}

.phpで終わるリクエストに対して、PHPプロセスに転送します。

fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;

fastcgi_passディレクティブでPHP-FPMソケットへのパスを指定します。

fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;

fastcgi_paramディレクティブで以下のようなスクリプトのファイル名を設定します。

/var/www/html/example/public/index.php

include fastcgi_params;

fastcgi_paramsファイルをincludeします。さまざまなfastcgi_paramが設定済みです。

location ~ /\.(?!well-known).*

location ~ /\\.(?!well-known).* {
    deny all;
}

.well-knownディレクトリ以外のすべてのドットファイルへのアクセスを拒否します。

Laravel公式のNginxのconfを設定変更する

Docker利用(fastcgi_pass)

Dockerの利用するなら、以下のように変更します。

fastcgi_pass <service_name>:<port>;

phpというサービス名で、FastCGIデフォルトポートを利用するなら以下のように設定します。

fastcgi_pass php:9000;

ロードバランサを使用しない場合のSSL対応

本番運用では一般的にロードバランサを使用します。その場合、SSL通信が必要な箇所はクライアント↔Nginxではなく、クライアント↔ロードバランサです。ただ、何らかの理由でロードバランサを使用しないならNginxでの設定が必要です。

以下のように設定します。

listen 443 ssl;
ssl_certificate     /etc/nginx/conf.d/sample.com.pem;
ssl_certificate_key /etc/nginx/conf.d/sample.com-key.pem;

まとめ

今回の記事では、Laravel公式のNginxのconfを解説しました。そのあとに補足として、DockerやSSL対応についても説明しました。

nginx実践入門

Nginxの構築と運用に関する幅広い知識を得られます。リアルなユースケースを元にした具体例が豊富に紹介されており、初心者から上級者まで、あらゆるレベルのエンジニアにとって実際の問題解決に役立ちます。

PHPフレームワークLaravel Webアプリケーション開発 バージョン8.x対応

既にLaravelの基本を知っていてスキルアップを図りたい開発者にとって、かなりおすすめです。クリーンなコーディング、保守性、テストの容易さなど、Laravelの提供する現代的なWeb開発のベストプラクティスを体系的に学べる内容が含まれています。

Takaharu Niki

・Webエンジニア6年目。
・バックエンドを中心に、フロントエンドやDevOps業務も経験。
・現在は、自社サービス企業のテックリードとして従事。

Takaharu Nikiをフォローする
Laravel
Takaharu Nikiをフォローする
アントレプログラマー
タイトルとURLをコピーしました