2022年10月21日金曜日

Vue Routerの二つのHIstory Modeについて

Vue Router のHistory Mode(ページ履歴動作)には、従来からhashモードとHTML5 historyモードの二つがありました。hashモードは、#で指定されるURLフラグメントを用いる形式で、HTML5 historyモードはURLフラグメントを使用しません。

Vue Router Ver 3.xの既定はhashモードでしたが、Ver 4.xでは、HTML5 historyモードの使用が推奨されています(Different History modes)。

意識せずにVue Router Ver 4.xを使用したアプリケーションをつくって、ページをリロードしたら404エラーが返ってきて、ちょっと慌てました。意識してhistoryモードにした覚えがないので、URLに#がなくなって、「お、#がなくなってすっきりしたな」などと喜んでいたら、単にHTML5 historyモードになっていただけでした。

HTML5 historyモードは、当然ながらサーバー側の設定が必要なので、Different History modesの、設定例(今回はApache)にしたがって設定しますが、当該アプリケーションはサーバーのサブフォルダーに設置されていたので、以下の記載に従いました。

Note: The following examples assume you are serving your app from the root folder. If you deploy to a subfolder, you should use the publicPath option of Vue CLI and the related base property of the router. You also need to adjust the examples below to use the subfolder instead of the root folder (e.g. replacing RewriteBase / with RewriteBase /name-of-your-subfolder/).

示されていたApacheの設定例

<IfModule mod_negotiation.c>
  Options -MultiViews
</IfModule>

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

上記のNoteに従って設定例のRewriteBaseを、

RewriteBase /name-of-your-subfolder/

に置き換えてリロード!→404エラー!

最後のRewriteRuleを、

RewriteRule . index.html [L]

に変更しないとだめだよね…。