Skip to content

Commit 1a6ce7b

Browse files
committedAug 21, 2023
feat: add canonicalDomain config
1 parent 4bb23ed commit 1a6ce7b

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed
 

‎module/src/module.ts

+23-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {
2-
addImports, addPlugin,
2+
addImports, addPlugin, addServerHandler,
33
createResolver,
44
defineNuxtModule,
55
installModule, useLogger,
@@ -12,6 +12,17 @@ export interface ModuleOptions {
1212
enabled: boolean
1313
debug: boolean
1414
splash: boolean
15+
/**
16+
* When enabled, it will redirect any request to the canonical domain (site url) using a 301 redirect on non-dev environments.
17+
*
18+
* E.g if the site url is 'www.example.com' and the user visits 'example.com',
19+
* they will be redirected to 'www.example.com'.
20+
*
21+
* This is useful for SEO as it prevents duplicate content and consolidates page rank.
22+
*
23+
* @default false
24+
*/
25+
canonicalDomain: boolean
1526
}
1627

1728
const Modules = [
@@ -26,17 +37,18 @@ const Modules = [
2637

2738
export default defineNuxtModule<ModuleOptions>({
2839
meta: {
29-
name: 'nuxt-seo-kit',
40+
name: 'nuxtseo',
3041
compatibility: {
3142
nuxt: '^3.6.5',
3243
bridge: false,
3344
},
34-
configKey: 'seoKit',
45+
configKey: 'seo',
3546
},
3647
defaults(nuxt) {
3748
return {
3849
enabled: true,
3950
debug: false,
51+
canonicalDomain: false,
4052
splash: nuxt.options.dev,
4153
}
4254
},
@@ -79,6 +91,14 @@ export default defineNuxtModule<ModuleOptions>({
7991
// @ts-expect-error untyped
8092
nuxt.options.experimental.headNext = true
8193

94+
// add redirect middleware
95+
if (config.canonicalDomain && nuxt.options.dev === false) {
96+
addServerHandler({
97+
handler: resolve('./runtime/middleware/redirect'),
98+
middleware: true,
99+
})
100+
}
101+
82102
if (config.splash) {
83103
logger.log('')
84104
let latestTag = `v${version}`
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { defineEventHandler, sendRedirect } from 'h3'
2+
import { joinURL } from 'ufo'
3+
import { useNitroOrigin, useSiteConfig } from '#imports'
4+
5+
export default defineEventHandler((e) => {
6+
const siteConfig = useSiteConfig(e)
7+
if (siteConfig.site) {
8+
const origin = useNitroOrigin(e)
9+
// if origin doesnt match site, do a redirect
10+
if (!siteConfig.site.startsWith(origin)) {
11+
const url = new URL(e.path, origin)
12+
url.hostname = siteConfig.site
13+
return sendRedirect(e, joinURL(siteConfig.site, url.pathname), 301)
14+
}
15+
}
16+
})

0 commit comments

Comments
 (0)
Please sign in to comment.