Skip to content

Commit

Permalink
fix: avoid infinite redirects with redirectToCanonicalSiteUrl redir…
Browse files Browse the repository at this point in the history
…ects
  • Loading branch information
harlan-zw committed Jul 11, 2024
1 parent 159380f commit bac31a9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ export default defineNuxtModule<ModuleOptions>({
nuxt.options.experimental.headNext = true

// add redirect middleware
if (config.redirectToCanonicalSiteUrl) {
if (!nuxt.options.dev && config.redirectToCanonicalSiteUrl) {
addServerHandler({
handler: resolve('./runtime/nitro/middleware/redirect'),
middleware: true,
Expand Down
12 changes: 10 additions & 2 deletions src/runtime/nitro/middleware/redirect.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { defineEventHandler, sendRedirect } from 'h3'
import { defineEventHandler, sendRedirect, setHeader } from 'h3'
import { joinURL } from 'ufo'
import { useNitroOrigin, useSiteConfig } from '#imports'

Expand All @@ -8,8 +8,16 @@ export default defineEventHandler((e) => {
const siteConfigHostName = new URL(e.path, siteConfig.url).hostname
const origin = useNitroOrigin(e)
const originHostname = new URL(e.path, origin).hostname
// check for redirect header
if (e.headers.get('x-nuxt-seo-redirected')) {
return
}
// if origin doesn't match site, do a redirect
if (originHostname !== siteConfigHostName)
// we need to avoid redirect loops so check if the origin is already a redirect
if (originHostname !== siteConfigHostName && originHostname !== new URL(e.path, origin).hostname) {
// set a header to avoid redirect loops
setHeader(e, 'x-nuxt-seo-redirected', 'true')
return sendRedirect(e, joinURL(siteConfig.url, e.path), 301)
}
}
})

0 comments on commit bac31a9

Please sign in to comment.