LoginSignup
2
2

More than 1 year has passed since last update.

Ruby on Railsの環境を構築する際のNginx設定ファイルのコマンド及びコード理解

Posted at

なぜ記事を書こうと思ったか

Nginx 用の設定ファイルを作成する際にコマンド及びコードの理解を備忘録として残すため。

default.confのコマンド説明

default.conf

upstream puma {
    server app:3000;
  }

server {
    listen 80;
    server_name localhost;

    access_log /var/log/nginx/access.log;
    error_log  /var/log/nginx/error.log;

    root /app/public;

    location @puma {
      proxy_set_header X-Real-IP  $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_pass http://puma;
    }

    location / {
      try_files $uri @puma;
    }

    location ~ ^/(assets|packs)/ {
      gzip_static on;
      expires max;
      add_header Cache-Control public;
    }

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

    error_page 404 /404.html;
    location = /404.html {
    }

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

以下にコマンド及びコードの解説を致します。

  • server app:3000
    upstreameでpumaグループを定義、個々のサーバーに app:3000を設定

  • listen 80
    デフォルトでは、 Nginx HTTP サーバーは受信接続を待機し、標準のWebポートを表すポート 80 にバインドする。

  • server_name localhost
    ホスト名を指定

  • access_log /var/log/nginx/access.log error_log /var/log/nginx/error.log
    access_logとerror_logのパス指定

  • root /app/public
    ドキュメントルートを指定

  • location
    locationはURI毎に異なる設定をできるようにする

  • proxy_set_header
    プロキシーサーバに送られるリクエストヘッダの フィールドを再定義、あるいは追加する。

  • proxy_pass http://puma
    リクエストをHTTP プロキシされたサーバに送る

  • try_files $uri @puma
    左から順に実体ファイルが存在しているかどうかを探し、あればそのままそのファイルを参照してくれる

  • gzip_static on
    圧縮していない物を圧縮し、既に圧縮済みのファイル(e.g. xxx.js.gz)があればそれをそのまま配信する

  • expires max
    クライアントキャッシュの有効期限設定

  • add_header Cache-Control public
    下位のレベル(location)にadd_headerを設定した場合、上位のレベル(server)のadd_headerは破棄される。
    拡張子 gif、jpeg、jpg、png、ico、svg、css、jsのファイルをキャッシュする

  • access_log off log_not_found off
    アクセスログ、エラーログを捨てる

  • error_page 404 /404.html
    エラーページを作成する。

最後に

何か間違っている所や気になった事があれば、コメントいただけると嬉しいです。

参考記事

2
2
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
2
2