LoginSignup
6
7

More than 5 years have passed since last update.

ルートとサブディレクトリに別々のrouter付きReactアプリを展開するnginxの設定

Posted at

Reactでアプリケーションを実装していて、 hoge.com/* にはユーザー向けReactアプリ、 hoge.com/admin/* には管理者向けのような構成にしたいと思ったことはないですか?僕はあります。

これらのアプリをnginxをbaseとしたDocker imageとしてデプロイしようとした時、nginxの設定にとても苦しんだのでここに書き記しておきます。

nginx.conf

server_tokens off;

server {
    listen 80 default_server;
    server_name localhost;

    location /admin {
        root /usr/share/nginx/html/admin;
        index index.html;
        try_files $uri $uri/ /index.html /usr/share/nginx/html/admin/index.html;

        location ~* \.(?:manifest|appcache|html?|xml|json)$ {
            expires -1;
        }

        location ~* \.(?:css|js)$ {
            try_files $uri =404;
            expires 1y;
            access_log off;
            add_header Cache-Control "public";
        }

        location ~ ^.+\..+$ {
            try_files $uri =404;
        }
    }

    location / {
        root /usr/share/nginx/html/frontend;
        index index.html;
        try_files $uri $uri/ /index.html;

        location ~* \.(?:manifest|appcache|html?|xml|json)$ {
            expires -1;
        }

        location ~* \.(?:css|js)$ {
            try_files $uri =404;
            expires 1y;
            access_log off;
            add_header Cache-Control "public";
        }

        location ~ ^.+\..+$ {
            try_files $uri =404;
        }
    }
}

こんな感じになりました。
adminの設定の箇所がキモです。 adminの設定は location / より上に書きましょう。

また、 try_files で、 /index.html を指定しつつ、絶対パスの /usr/share/nginx/html/admin/index.html も追加で指定する必要があります。

この指定がないと、 /admin/下層ページ にアクセスした際 index.html がないとみなされ、 location / の設定を見に行ってしまい、 /index.htmlindex.js によってURLが解釈されてしまします。

こんな感じでした。
特殊なことをやろうとするとWebに情報があまりなくて困りますね。

ので、特殊なことをやった際はどんどんWebに残していこうと思います。

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