記事概要
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 }
]
…
最後に
このリダイレクト処理は色々応用が利きそう。