Skip to content

Commit

Permalink
feat: add canonicalDomain config
Browse files Browse the repository at this point in the history
  • Loading branch information
harlan-zw committed Aug 21, 2023
1 parent 4bb23ed commit 1a6ce7b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
26 changes: 23 additions & 3 deletions module/src/module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {
addImports, addPlugin,
addImports, addPlugin, addServerHandler,
createResolver,
defineNuxtModule,
installModule, useLogger,
Expand All @@ -12,6 +12,17 @@ export interface ModuleOptions {
enabled: boolean
debug: boolean
splash: boolean
/**
* When enabled, it will redirect any request to the canonical domain (site url) using a 301 redirect on non-dev environments.
*
* E.g if the site url is 'www.example.com' and the user visits 'example.com',
* they will be redirected to 'www.example.com'.
*
* This is useful for SEO as it prevents duplicate content and consolidates page rank.
*
* @default false
*/
canonicalDomain: boolean
}

const Modules = [
Expand All @@ -26,17 +37,18 @@ const Modules = [

export default defineNuxtModule<ModuleOptions>({
meta: {
name: 'nuxt-seo-kit',
name: 'nuxtseo',
compatibility: {
nuxt: '^3.6.5',
bridge: false,
},
configKey: 'seoKit',
configKey: 'seo',
},
defaults(nuxt) {
return {
enabled: true,
debug: false,
canonicalDomain: false,
splash: nuxt.options.dev,
}
},
Expand Down Expand Up @@ -79,6 +91,14 @@ export default defineNuxtModule<ModuleOptions>({
// @ts-expect-error untyped
nuxt.options.experimental.headNext = true

// add redirect middleware
if (config.canonicalDomain && nuxt.options.dev === false) {
addServerHandler({
handler: resolve('./runtime/middleware/redirect'),
middleware: true,
})
}

if (config.splash) {
logger.log('')
let latestTag = `v${version}`
Expand Down
16 changes: 16 additions & 0 deletions module/src/runtime/server/middleware/redirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { defineEventHandler, sendRedirect } from 'h3'
import { joinURL } from 'ufo'
import { useNitroOrigin, useSiteConfig } from '#imports'

export default defineEventHandler((e) => {
const siteConfig = useSiteConfig(e)
if (siteConfig.site) {
const origin = useNitroOrigin(e)
// if origin doesnt match site, do a redirect
if (!siteConfig.site.startsWith(origin)) {
const url = new URL(e.path, origin)
url.hostname = siteConfig.site
return sendRedirect(e, joinURL(siteConfig.site, url.pathname), 301)
}
}
})

0 comments on commit 1a6ce7b

Please sign in to comment.