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.html 、 index.js によってURLが解釈されてしまします。
〆
こんな感じでした。
特殊なことをやろうとするとWebに情報があまりなくて困りますね。
ので、特殊なことをやった際はどんどんWebに残していこうと思います。