0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Nuxt.jsでのリダイレクト処理

Last updated at Posted at 2023-12-01

記事概要

Nuxt.jsでnuxt generateで生成した静的ファイルにアクセスすると、なぜかURLの末尾に必ず"/"が挿入されてしまう。

【例】
/hoge          ⇒  /hoge/
/hoge?key=val  ⇒  /hoge/?key=val

それの解決方法。

※nuxt.config.jsに、⇓この設定をしてもうまく行かず。

trailingSlash: false

環境

開発環境

OS : windows 10
Node : v18.18.0
仮想化: nvm 1.1.11
WebServer: go1.16.6 => "net/http"で作成

package.json


  "dependencies": {
    "@nuxt/content": "^1.0.0",
    "@nuxtjs/axios": "^5.13.6",
    "@nuxtjs/sitemap": "^2.4.0",
    "core-js": "^3.25.3",
    "nuxt": "^2.17.2",
    "vue": "^2.7.10",
    "vue-server-renderer": "^2.7.10",
    "vue-template-compiler": "^2.7.10",
    "vuetify": "^2.6.10"
  }

解決方法

redirect-moduleの導入で解決。参考URL【nuxtでのリダイレクト設定について

➀ redirect.jsを作成

plugins\redirect.js\redirect.js

export default function ({ route, redirect }) {
  if (route.path.slice(-1) === '/' && route.path !== '/') {
    const search = route.fullPath.match(/\?.*$/)
    if (search) {
      const redirectUrl = route.path.slice(0, -1) + search[0]
      return redirect(301, redirectUrl)
    } else {
      const redirectUrl = route.path.slice(0, -1)
      return redirect(301, redirectUrl)
    }
  }
}

参考にしたURLでは、"/"を付ける方法だが、今回は"/"を削除するのが目的。

➁ nuxt.config.jsにpluginsを追加


  plugins: [
    { src: '~plugins/redirect', ssr: false }
  ]

最後に

このリダイレクト処理は色々応用が利きそう。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?