LoginSignup
2
0

More than 5 years have passed since last update.

Docker+nginxでtry_filesを追加したい

Posted at

PWAのhistory APIを利用している場合、TOP以外のURLでリロードすると実体が存在しないため、404になってしまう。
※history APIは実際にはサーバーにアクセスせずに、ブラウザのURLを書き換えるというもの。

そのため、すべてのアクセスはindex.htmlなどの実体で受け止める必要がある。
vuejsではVueRouterのhistory mode, AngularのRouterではデフォルトでhistory APIを利用するので、これをやっておかないとTOPページが出たワーイからの別ページを作るときに404祭りになってアワアワすることになるよ!

APIの詳細はこいつ。 History - Web API | MDN - Mozilla

どうなるの?


TOPページ(vueのサンプル)
image.png


aboutページに遷移はOK
image.png


リロードすると、404になる。
image.png

どうすればいいの?

index.htmlにすべてを放り投げればよい。
nginxの設定にtry_filesを追加することでおkになる。
locationの中に書くのがよろしかろう。try_files $uri $uri/ /index.html;
これをやると本当の404もindex.htmlに持っていかれるのでjs側でなんとかしてください。

server {
    listen 80;
    server_name  localhost;

    charset utf-8;

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

Docker

Dockerのnginxを利用する場合、confファイルを作ってコピーする。
nginx-vhost-default.confに↑のようなconfファイルを用意して、コンテナにコピーしてあげる。
下から2行目だよね。

# Stage 0, "build-stage", based on Node.js, to build and compile the frontend
FROM node:11.3.0 as build-stage
WORKDIR /app
COPY package*.json /app/
RUN npm install --global npm@6.8.0 npx@10.2.0 && npm install
COPY ./ /app/
RUN npm run build -- --mode development

# Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx
FROM nginx:1.15
COPY ./nginx-vhost-default.conf /etc/nginx/conf.d/default.conf
COPY --from=build-stage /app/dist /usr/share/nginx/html

default.confはDockerですでに用意されていて、上書きしてしまうので元を知りたい方はこちらを参考にどうぞ。
https://github.com/nginxinc/docker-nginx/tree/master/stable/alpine

おまけ Apache2.2と2.4の場合

2.2の場合は頑張って書く。

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

2.4の場合はFallbackResourceが使えます。

<IfModule mod_rewrite.c>
    FallbackResource /
</IfModule>

2.2は2017年でエンドオブライフを迎えてますので使わないようにしてくださいね。

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