0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nginx⑦静的キャッシュの設定

Last updated at Posted at 2025-03-07

はじめに

Nginxを使用した静的キャッシュの設定をローカル環境で手軽に体感することを目的としておりますので、Nginxに初めて触れる方向けの内容となっております。

キャッシュとは

同じアクションを高速化するために、ソフトウェアなどで取り扱うデータを一時的に保存する仕組みのことです

静的キャッシュとは

サーバーやブラウザが静的コンテンツ(画像、CSS、JavaScriptなど)をキャッシュする手法です

環境

  • Ubuntu 24.04
  • nginx-1.26.3
  • 推奨される設定状態
    • sites-availablesites-enabledディレクトリが存在する
    • /etc/nginx/sites-enabled/内の設定ファイルがNginxの設定に組み込まれている
    • 静的ファイルが存在する

下記のサイトで上記のような環境にする方法が記載されております。

手順1:プロキシキャッシュの設定

/etc/nginx/sites-available/normal
server {
    listen 80;
    server_name localhost;

    # リクエストされた際にドキュメントがある場所
    root /path/to/static/files;
    index index.html;

    location ~ .*\.(html|jpg|gif|png|css|js) {
            expires 30d;
    }

    location / {
        try_files $uri $uri/ =404;
    }
}
  • location ~ .*\.(html|jpg|gif|png|css|js)
    • htmljpggifpngcssjsの拡張子を持つリクエストに対して適用されるlocationブロックを定義しています
  • expires 30d;
    • キャッシュを 30日間 ブラウザに保持させます(パフォーマンス向上)

静的キャッシュにおける注意点

動的コンテンツにはExpiresを設定しないでください。理由は、アクセスのたびに内容が変わる性質があり、Expiresを設定すると最新の情報が正しく表示されなくなってしまうからです。

手順2:sites-enabled/にシンボリックリンクを作成

sudo ln -s /etc/nginx/sites-available/normal /etc/nginx/sites-enabled/

手順3:設定の反映

sudo systemctl reload nginx

手順4:キャッシュの状態を確認する方法

  1. http://localhost:80にアクセスし、開発者ツールを開きます。
  2. ネットワークタブを選択します
  3. キャッシュ対象のリクエストを選択して、レスポンス ヘッダーExpiresが表示されるので、キャッシュの状態(例:Sun, 06 Apr 2025 06:21:12 GMT)を確認します

まとめ

以上で、静的キャッシュの設定ができました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?