LoginSignup
14
9

ReactでサブディレクトリにWebアプリを置くときの設定まとめ

Last updated at Posted at 2021-06-07

利用シーン

Reactでフロントを作ったとき、https://site.domainではなく、
https://site.domain/sub_dirctoryindex.jsindex.htmlを設置する場面。
そのままでは、大量のcontents404 Not Foundになります。

たくさんURLを書き換えるのは骨が折れるので、数か所の変更で済む方法はないのか?
情報源がいろいろあって分かりにくかったので、1ページにまとめました。

※下記で./はプロジェクトルートディレクトリを指します。

package.jsonを設定

./package.json"homepage": "/sub_dirctory/"を追加します。

./package.json
{
  "name": "project001",
  "version": "0.1.0",
  "private": true,
// -- any things
// -- any things
+  "homepage": "/sub_dirctory/"
}

historyを追加

Routingを行っているjsファイルにて、Router系のJSXのpropsであるhistoryに設定を行います。
この時、ライブラリhistory/createBrowserHistoryが必要です。
historyを使っていない場合は、ここで新規にインストールします。
npmを使ってインストールする場合のコマンドです。

terminal
npm install history

npmではなくyarnの場合です。

terminal
yarn add history

次に、該当箇所に変更を入れます。

./src/app.js
// -- any things
import MiniApp_001 from 'miniapp_001';
import MiniApp_002 from 'miniapp_002';
import { Router, Route, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';
// -- any things
const customizedhistory = createBrowserHistory({ basename: '/sub_dirctory' });
// -- any things
class App extends React.Component {
    render() {
        return (
// -- any things
            <Router history={customizedhistory}>
                <Switch>
                    <Route exact path="/" component={MiniApp_001} />
                    <Route exact path="/test" component={MiniApp_002} />
                    <Route component={NotFound} />
                </Switch>
            </Router>
// -- any things
        );
    }
}
export default App;

上から順に説明していくと、
まず、先ほどインストールしたhistoryからcreateBrowserHistoryをインポートします。

import {createBrowserHistory} from "history"

次に、createBrowserHistoryを使って、/subdirectoryを指定するためのオブジェクトcustomizedhistoryを用意します。

const customizedhistory = createBrowserHistory({ basename: '/sub_dirctory' });

JSXオブジェクトであるRouterpropsに、historyがあります。このhistoryの値にcustomizedhistoryを設定します。

<Router history={customizedhistory}>

この例ではRouterを用いていますが、他にBrowserRouterHashRouterMemoryRouterStaticRouterがあります。いずれも同様に設定可能です。

ちなみに、JSXのネストの根っ子にRouterは1個あればいいです。<Switch/>設置するたびに<Router/>設置すると沼にハマります。

.htaccessを設定する

Apache の場合にはhtaccessの設定を必要とします。

./public/.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ ./index.html [QSA,L]

Rewrite系構文のドキュメント

nginx.confを設定する

nginxの場合はnginx.confに下記設定を追記する必要があります。

nginx.conf
location ^~ /sub_dirctory{
   alias /var/www/project001/build;
   try_files $uri $uri/ /sub_dirctory/index.html;
}

まとめ

多くのWebフレームワークでは、ドメインのルートに設置する前提で設計されています。もちろんReactも例外ではありません。デフォルトでは/に設定されています。しかし、いくつか設定すれば簡単に変更できます。

多くのWebフレームワークがDRYの原則から生まれたようなもの。これが出来るのは当たり前品質かもしれませんね。少しぐらいの誤差は吸収できるように、ロバストなコードを使えばサボれる。サボりは大切です。

Excelsior!

14
9
2

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
14
9