LoginSignup
0
0

More than 3 years have passed since last update.

Vue.jsの404リダイレクト

Posted at

やりたかったこと。

  • Vue.jsで404ページへのリダイレクト
  • 404ページは静的HTML
  • レスポンスコードも404

結果。

出来ませんでした...
(Vue.jsのv2)

妥協後の設定。

“レスポンスコードも404” は諦めました。
純粋にJavaScriptで404用のhtmlにリダイレクトするように...
リダイレクトになるので、ブラウザのアドレスバーが404用のhtmlに変わるのもダサい気もしましたが、諦めました。

1. routerの設定

静的HTMLに遷移させるので、リダイレクト先のcomponentなどは不要。

// 404
{
  name: 'FileNotFound',
  path: '*'
}
2. router.beforeEachの設定

routerのredirectだとVue内の遷移になるので、router.beforeEachで指定する。
この時、nextだとredirectと同じになるので、window.locationを使用する。

router.beforeEach((to, from, next) => {
  if (to.name === 'FileNotFound') {
    window.location = '/err/404.html'
    return
  }
3. Apacheの設定

window.locationで遷移したページの場合は、404エラーに書き換える。

所感

アドレスバーはアクセスした時のURLのままが良かった...

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