一.身份验证
内容较多,请参考上一节文章 基于nodejs+vuetify3+ts+nuxt框架集成模块组件解析-身份验证-优快云博客
二.SEO优化
SEO简介
SEO优化,即搜索引擎优化(Search Engine Optimization),是一种通过优化网站或链接文案的内容和结构,使其在搜索引擎的自然搜索结果中排名更高,从而获取更多自然流量(非付费流量)的技术。
提示 : 本文章节内容较多,略显混乱,可根据目录结构看
快速安装
1.通过npm或yarn安装@nuxtjs/seo
模块:
npm install @nuxtjs/seo
# 或者
yarn add @nuxtjs/seo
2.在 Nuxt 配置中引入 @nuxtjs/seo
接下来,你需要在nuxt.config.js
文件中引入并配置@nuxtjs/seo
模块:
export default {
modules: [
'@nuxtjs/seo',
],
// 你可以在这里添加额外的配置选项
seo: {
// 默认的SEO设置
title: '默认标题',
description: '默认描述',
ogTitle: '默认OG标题',
ogDescription: '默认OG描述',
twitterCard: 'summary_large_image', // 例如使用Twitter卡片类型
}
}
3.使用 @nuxtjs/seo 提供的方法和组件
在页面中使用 SEO 元数据
在Nuxt3中,你可以在页面或组件中使用<Head>
标签来定义页面的SEO元数据。结合@nuxtjs/seo
,你可以这样设置:
<template>
<div>
<h1>我的页面</h1>
</div>
</template>
<script setup>
import { useHead } from '@nuxtjs/seo';
useHead({
title: '我的页面标题',
meta: [
{ name: 'description', content: '这是我的页面描述' },
{ property: 'og:title', content: '我的页面OG标题' },
{ property: 'og:description', content: '这是我的页面OG描述' }
]
});
</script>
全局设置 SEO 配置
你也可以在nuxt.config.js
的全局配置中设置一些默认的SEO元数据,这样在每个页面中都可以继承这些设置,同时还可以通过页面特定的设置覆盖它们。例如:
export default {
modules: [
'@nuxtjs/seo',
],
seo: {
titleTemplate: '%s | 我的网站', // 使用模板来设置标题格式,%s 将被页面的title替换
description: '这是网站的默认描述', // 默认描述,可以被页面覆盖
twitterCard: 'summary_large_image', // 默认Twitter卡片类型,可以被页面覆盖
}
}
测试和调试 SEO 设置
完成上述步骤后,你应该测试你的页面以确保SEO元数据正确设置。你可以使用各种SEO工具(如Google Search Console, Moz, SEMrush等)来检查你的元数据是否正确显示。同时,你也可以在浏览器的开发者工具中查看HTML源代码来验证元数据是否正确嵌入。
附加:使用 Vuetify3 和 Vue3 的集成注意事项
虽然 Vuetify3 是基于Vue3构建的,但在Nuxt3中与@nuxtjs/seo
集成使用时通常不需要特别处理,因为Nuxt3已经很好地支持了Vue3的组件和插件系统。只需按照上述步骤操作即可。确保你的Vuetify组件和Vue3组件在你的Nuxt页面中正确使用,并且遵循Nuxt的异步数据和生命周期钩子(如asyncData
, fetch
等)的使用。
SEO优化方式
以下是进行SEO优化的关键步骤和技巧:
-
关键词优化:
- 准确定位关键词,并考虑扩展关键词的作用,因为扩展关键词有时能带来比主关键词更多的流量,且更易于优化排名。
- 在网页的标题(Title)、元标签(Meta)、内容、链接等位置合理布局关键词,但要避免关键词堆砌,一般同样的关键词在Title中最好不要超过3次。
-
结构优化:
- 提供清晰的网站结构,为用户和搜索引擎提供一个易于导航的网站地图。
- 确保每个网页都可以通过至少一个静态文本链接打开,避免使用图片或Flash中的链接,以免导致网页索引不全。
-
内容优化:
- 内容是网页的灵魂,应确保内容原创、有价值且与用户搜索意图相关。
- 合理地将关键词编排到网页内容中,但要保持自然,避免过度优化,关键词密度建议控制在3%~7%之间。
-
链接优化:
- 使用带有关键词的文本链接,避免损坏的链接,并确保链接书写格式的正确。
- 控制网页中的链接数量在合理范围内,一般小于100个。
-
URL优化:
- URL中应包含关键词,这有助于增加关键词在搜索引擎中的表现。
- 注意URL的长度和可读性,尽量简洁明了。
技术优化
1.通过SEO sitemap站点地图组件更好优化搜索引擎抓取方式
2.通过xml插件转换类将前端html页面转换为XML结构,方便搜索引擎更容易抓取关键词和网页内容。
-
其他注意事项:
- 定期更新网站内容,保持网站的活跃度和新鲜度。
- 关注搜索引擎的算法更新和行业动态,及时调整优化策略。
- 提高网站的用户体验,如加载速度、响应性、易用性等,这也有助于提升搜索引擎排名。
通过遵循以上步骤和技巧,可以有效地提升网站在搜索引擎中的排名,从而获取更多的自然流量和潜在客户。
下面列举 nuxt3 框架中集成的性价比较高SEO模块组件 ,并一一列举解析安装和使用方法。
注:本文中代码示例仅做参考,请根据实际项目开发的框架和写法,自行修改
@nuxtjs/seoji集成模块
next SEO模块是面向next的一体化SEO解决方案。它将6个SEO模块和最佳实践组合到一个模块中,需要最少的文件来配置,实现开箱即用的效果。
组成模块
🤖 @nuxtjs/robots - 管理网站爬行
📄 @nuxtjs/sitemap - sitemap .xml支持
🔎 nuxt-schema-org - 为SEO生成Schema.org JSON-LD
△ nuxt-seo-utils - 实验性SEO元功能
🖼️ nuxt-og-image - 生成动态社交分享图片
✅ nuxt-link-checker - 检查断开的链接
安装和使用
nuxt3框架中安装 @nuxtjs/seo 依赖到你的项目:
npx nuxi@latest module add seo
pnpm安装
pnpm i @nuxtjs/seo
您需要手动将模块添加到next配置中。
示例 nuxt.config.ts
export default defineNuxtConfig({
modules: [
'@nuxtjs/seo',
],
})
官方文档 默认模块功能指南
对于复制和演示环境,您可以使用 next SEO Basic Reproduction 模板。
next SEO模块只是一个别名,它将所有其他SEO模块组合到一个单独的安装中。
示例
// This is all it does!
export default defineNuxtModule({
async setup() {
for (const module of modules) {
await installModule(await resolvePath(module), {})
}
},
})
在使用next SEO时,您可以自由地使用此别名或单独安装模块。选择是你的,因为所有的网站都是不同的,有不同的要求。
网站配置
为了确保所有模块都能很好地协同工作,next SEO包含了一个名为Site Config的模块。该模块本身在所有模块中使用,以确保它们被正确配置。
您不需要手动安装此模块,它会在您安装任何SEO模块时自动安装。
相应模块组件
虽然大多数模块都是开箱即用的,但根据您网站的要求,可能需要一些配置。下面简单记录6个组件和相关功能的使用方法:
一.网站地图 - Sitemap
网站地图
Vue和next中的站点地图
了解如何在Vue和next应用程序中创建和维护站点地图。
介绍
xml文件可以帮助搜索引擎发现和理解您站点的页面。虽然不是必需的,但对于大型网站和那些内容更新频繁的网站来说,它尤其有价值。
✅适用于:
大型网站(100页以上)
频繁更新的内容
复杂的站点结构
新网站需要更快的索引
快速安装使用
推荐nuxt安装
npx nuxi module add @nuxtjs/sitemap
其他命令安装
npm i @nuxtjs/sitemap
#
yarn add @nuxtjs/sitemap
#
pnpm i @nuxtjs/sitemap
#
bun i @nuxtjs/sitemap
其他安装配置
其他命令安装需要手动配置 nuxt.config.ts
export default defineNuxtConfig({
modules: [
'@nuxtjs/sitemap',
],
})
快速设置
创建一个基本站点地图,将其添加到您的公共目录中:
public/
sitemap.xml
添加您的网址:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://mysite.com/</loc>
<lastmod>2024-11-03</lastmod>
</url>
</urlset>
动态实现
对于内容不断变化的站点,动态生成站点地图:
示例 vue
// example using Vite SSR
function createServer() {
const app = express()
app.get('/sitemap.xml', (req, res) => {
const urls = [
{ url: '/', lastmod: '2024-12-10' },
{ url: '/about', lastmod: '2024-12-15' }
]
const sitemap = `
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
${urls.map(page => `
<loc>https://mysite.com${page.url}</loc>
<lastmod>${page.lastmod}</lastmod>
`).join('\n')}
</url>
</urlset>
`
res.type('application/xml').send(sitemap)
})
}
示例 nuxt
// server/routes/sitemap.xml.ts
export default defineEventHandler(async () => {
// Fetch your dynamic URLs here
const urls = [
{ url: '/', lastmod: '2024-12-10' },
{ url: '/about', lastmod: '2024-12-15' }
]
return setResponseHeader(event, 'content-type', 'application/xml')`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${urls.map(page => `
<url>
<loc>https://mysite.com${page.url}</loc>
<lastmod>${page.lastmod}</lastmod>
</url>
`).join('\n')}
</urlset>`
})
next Sitemap模块可以自动处理这个问题。
了解站点地图
站点地图由以下关键元素组成:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://mysite.com/page</loc>
<lastmod>2024-11-03</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
</urlset>
元素解释
loc:页面的URL(必需的)
lastmod:最后一次修改页面的时间(推荐)
changefreq:页面更改的频率(可选)
priority:从0.0到1.0的相对重要性(可选)
注意:谷歌只使用lastmod标签- changefreq和priority被忽略。
重要事项
每个站点地图限制为50,000个url
必须在UTF-8编码
url必须与规范url完全匹配
所有url必须来自相同的协议(HTTP/HTTPS)
需要绝对url
未压缩的文件大小限制为50MB
常见模式
多个站点地图
对于超过50,000个url的站点,使用站点地图索引:
示例
<?xml version="1.0" encoding="UTF-8"?>
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>https://mysite.com/products-sitemap.xml</loc>
<lastmod>2024-11-03</lastmod>
</sitemap>
<sitemap>
<loc>https://mysite.com/blog-sitemap.xml</loc>
<lastmod>2024-11-03</lastmod>
</sitemap>
</sitemapindex>
新闻站点地图
对于新闻站点,使用news命名空间:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">
<url>
<loc>https://mysite.com/article</loc>
<news:news>
<news:publication>
<news:name>Site Name</news:name>
<news:language>en</news:language>
</news:publication>
<news:publication_date>2024-11-03T12:00:00+00:00</news:publication_date>
<news:title>Article Title</news:title>
</news:news>
</url>
</urlset>
图片站点地图
对于图片较多的网站:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
<loc>https://mysite.com/page</loc>
<image:image>
<image:loc>https://mysite.com/image.jpg</image:loc>
<image:title>Image Title</image:title>
</image:image>
</url>
</urlset>
测试
使用谷歌搜索控制台
1.在谷歌搜索控制台提交您的站点地图
2.检查“Sitemaps”报告:
覆盖率统计数据
索引错误
发现url
重要的检查
验证XML语法
确保所有url都是可访问的(而不是404、500等)
检查url是否匹配规范标记
验证lastmod日期是否准确
确认正确的字符编码
相关
Robots.txt Guide - 控制爬虫访问
Meta Robots Guide - 页面级爬虫控制
Crawler Control - 完成指南管理网络爬虫
数据源 - Data Sources
根据你的应用数据源 (Data Sources) 在 /sitemap.xml 生成一个站点地图。
当预渲染或使用静态路由时,不需要配置,它会自动为您生成一个站点地图。
如果您有动态路由,则需要为动态url设置处理程序(Dynamic URLs)。
数据源
站点地图中的每个URL都属于一个源。
源可以是用户源或应用程序源。
应用程序源
应用程序源是从你的应用程序中自动生成的源。这些源的存在是为了使模块的使用更方便,但也可能会成为阻碍。 文件功能示例:
next:pages——静态分析应用程序的页面
next: preender -预呈现的url
next:route-rules -路由规则中的url
@nuxtjs/i18n:pages -当使用next i18n的页面配置时。有关详细信息,请参阅 Nuxt I18n 。
@nuxt/content:文档驱动-当使用文档驱动模式时。有关更多详细信息,请参阅 Nuxt Content 。
禁用应用程序源
通过使用excludeAppSources配置,你可以选择单独或全部退出应用程序源。
示例 禁用所有应用程序源 (disable all app sources)
export default defineNuxtConfig({
sitemap: {
// exclude all app sources
excludeAppSources: true,
}
})
示例 禁用页面应用程序源代码 (disable page app source)
export default defineNuxtConfig({
sitemap: {
// exclude static pages
excludeAppSources: ['nuxt:pages'],
}
})
用户来源
当使用一个没有使用预呈现发现的动态路由的站点时,您将需要提供自己的源。
可以使用下面不同方法实现:
1. 构建时:提供一个url函数
如果在构建时只需要站点地图数据并发,那么提供url函数是提供自己的数据源的最简单方法。
示例 nuxt.config.ts
export default defineNuxtConfig({
sitemap: {
urls: async () => {
// fetch your URLs from a database or other source
const urls = await fetch('https://example.com/api/urls')
return urls
}
}
})
2. 运行时:提供一个源数组
如果需要站点地图数据在运行时始终是最新的,则需要显式地提供自己的数据源。
源是一个将被获取的URL,预计将返回带有Sitemap URL条目数组的JSON或XML站点地图。
单站点地图 (single sitemap)
export default defineNuxtConfig({
sitemap: {
sources: [
// create our own API endpoints
'/api/__sitemap__/urls',
// use a static remote file
'https://cdn.example.com/my-urls.json',
// hit a remote API with credentials
['https://api.example.com/pages/urls', { headers: { Authorization: 'Bearer <token>' } }]
]
}
})
多站点地图 (multiple sitemaps)
export default defineNuxtConfig({
sitemap: {
sitemaps: {
foo: {
sources: [
'/api/__sitemap__/urls/foo',
]
},
bar: {
sources: [
'/api/__sitemap__/urls/bar',
]
}
}
}
})
国际化 - Nuxt I18n
开箱即用,机器人模块将直接与@nuxtjs/i18n集成。您将需要使用i18n模块的v8+版本。
自动本地化允许/不允许
该模块将根据您的i18n配置自动定位allow和disallow路径。
如果您提供了一个未本地化的allow或disallow路径,如果您的i18n配置允许,它将为您本地化。
示例 nuxt.config.ts
export default defineNuxtConfig({
robots: {
disallow: ['/secret', '/admin'],
},
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'en',
strategy: 'prefix',
}
})
这将生成以下输出:
示例 robots.txt
User-agent: *
Disallow: /en/secret
Disallow: /en/admin
Disallow: /fr/secret
Disallow: /fr/admin
选择退出本地化
如果你想退出本地化,有两个选择:
选择退出一组
您可以为组提供_skipI18n选项,以禁用仅针对该组的本地化。
示例
export default defineNuxtConfig({
robots: {
groups: [
{
disallow: [
'/docs/en/v*',
'/docs/zh/v*',
'/forum/admin/',
'/forum/auth/',
],
_skipI18n: true,
},
],
},
})
选择退出i18n全球
通过提供autoI18n: false选项,您将禁用所有i18n本地化分割。
示例
export default defineNuxtConfig({
robots: {
autoI18n: false,
}
})
18n特性
sitemap模块将自动生成一个多站点地图,每个地区都有自己的站点地图。
开箱即用,该模块与 @nuxtjs/i18n 和 nuxt-i18n-micro 集成,无需任何额外配置。
然而,I18n很棘手,您可能需要修改一些选项以获得最佳结果。
18n模式
自动I18n多站点地图
当满足某些条件时,sitemap模块将自动为每个地区生成一个站点地图:
如果不使用no_prefix策略 ,或者如果你使用不同的域名, 您还没有配置站点地图选项
这看起来像:
> ./sitemap_index.xml
> ./en-sitemap.xml
> ./fr-sitemap.xml
# ...etc
这些站点地图将包括应用程序源。next:pages源将自动为您的页面确定正确的替代方案。
如果你需要退出应用源,使用excludeAppSources: true。
I18n页面
如果您已启用i18n。页面在i18n配置中,那么sitemap模块将使用该配置自动生成单个站点地图。
这个站点地图将不包括应用程序源。
您可以使用源代码添加其他url。
i18n的动态url
为了简化站点地图输出,您提供的任何动态url都不包含i18n数据,并且只存在于默认的区域设置站点地图中。
为了帮助您做到这一点,该模块提供了两个选项:_i18nTransform和_sitemap。
如果您希望模块将单个URL转换为它的所有i18n变体,可以提供_i18nTransform: true选项。
示例 server/api/__sitemap__/urls.ts
export default defineSitemapEventHandler(() => {
return [
{
loc: '/about-us',
// will be transformed into /en/about-us and /fr/about-us
_i18nTransform: true,
}
]
})
或者,您可以使用_sitemap指定希望在哪个地区的站点地图中包含URL。
示例 server/api/__sitemap__/urls.ts
export default defineSitemapEventHandler(() => {
return [
{
loc: '/about-us',
_sitemap: 'en',
}
]
})
调试Hreflang
默认情况下,XML样式表不显示hreflang标记。您需要查看页面源代码才能看到它们。
别担心,搜索引擎仍然可以看到这些。
如果您想直观地看到hreflang标记计数,您可以自定义UI (Customising the UI)。
export default defineNuxtConfig({
sitemap: {
xslColumns: [
{ label: 'URL', width: '50%' },
{ label: 'Last Modified', select: 'sitemap:lastmod', width: '25%' },
{ label: 'Hreflangs', select: 'count(xhtml)', width: '25%' },
],
}
})
有关更多信息,请参见 i18sitemap 。
动态URL端点
使用运行时API端点为站点地图生成动态url。
简介
在某些情况下,比如使用CMS,您可能需要实现一个端点,以使您的所有站点url对模块可见。
为此,您可以向模块提供用户源。这些可以是JSON响应,也可以是XML站点地图。
XML站点地图
如果提供的是XML站点地图,则可以使用sources选项向站点地图提供URL。
示例 nuxt.config.ts
export default defineNuxtConfig({
sitemap: {
sources: [
'https://example.com/sitemap.xml',
]
}
})
处理外部API的动态url
当您的源是一个返回动态url的第三方API时,您有两个选项:
1.将端点直接添加到源配置中——对于已经以正确格式返回数据的端点来说很好
2.创建一个返回url的API端点——当您必须转换数据或实现自己的缓存时,这是必需的
1. 使用源配置
如果你要获取的URL需要任何额外的头文件才能工作,你可以提供一个数组形式的源,其中第二个选项是获取选项。
示例 nuxt.config.ts
export default defineNuxtConfig({
sitemap: {
sources: [
// fetch from an unauthenticated endpoint
'https://api.example.com/pages/urls',
// fetch from an authenticated endpoint
[
'https://authenticated-api.example.com/pages/urls',
{ headers: { Authorization: 'Bearer <token>' } } // fetch options
]
]
}
})
2. 创建您自己的端点
2.1 创建一个新的API端点
在这个代码片段中,我们使用defineSitemapEventHandler helper来创建一个新的API端点。
这是一个用于强制TypeScript类型的defineEventHandler的简单包装器。
单站点
import { defineSitemapEventHandler } from '#imports'
import type { SitemapUrlInput } from '#sitemap/types'
// server/api/__sitemap__/urls.ts
export default defineSitemapEventHandler(() => {
return [
{
loc: '/about-us',
// will end up in the pages sitemap
_sitemap: 'pages',
},
] satisfies SitemapUrlInput[]
})
多站点
import { defineSitemapEventHandler } from '#imports'
import type { SitemapUrl } from '#sitemap/types'
export default defineSitemapEventHandler(async () => {
const [
posts,
pages,
] = await Promise.all([
$fetch<{ path: string }[]>('https://api.example.com/posts')
.then(posts => posts.map(p => ({
loc: p.path,
// make sure the post ends up in the posts sitemap
_sitemap: 'posts',
} satisfies SitemapUrl))),
$fetch<{ path: string }[]>('https://api.example.com/pages')
.then(posts => posts.map(p => ({
loc: p.path,
// make sure the post ends up in the posts sitemap
_sitemap: 'pages',
} satisfies SitemapUrl))),
])
return [...posts, ...pages]
})
2.2 将端点添加到next .config.ts中
单站点地图来源
示例
export default defineNuxtConfig({
sitemap: {
sources: [
'/api/__sitemap__/urls',
]
}
})
多站点地图来源
示例
export default defineNuxtConfig({
sitemap: {
sitemaps: {
posts: {
sources: [
'/api/__sitemap__/urls/posts',
]
}
}
}
})
多站点地图
简介
默认情况下,该模块将生成一个/sitemap.xml文件,对于大多数网站来说,这是完美的。
然而,对于开始拥有数千个url的大型站点,引入多个站点地图可以帮助您更轻松地调试站点地图,还可以帮助搜索引擎更有效地抓取您的站点。
启用多个站点地图
如果你想生成多个站点地图,你可以使用sitemaps选项,它有两个选项:
object -启用手动分块。当您有明确的内容类型(页面,帖子等)或少于1000个url时建议使用
true -启用自动分块。当您有超过1000个url并且没有明确的内容类型时推荐使用。
示例 手动分块
export default defineNuxtConfig({
sitemap: {
// manually chunk into multiple sitemaps
sitemaps: {
posts: {
include: [
'/blog/**',
],
// example: give blog posts slightly higher priority (this is optional)
defaults: { priority: 0.7 },
},
pages: {
exclude: [
'/blog/**',
]
},
},
},
})
示例 自动分块
export default defineNuxtConfig({
sitemap: {
sitemaps: true,
// modify the chunk size if you need
defaultSitemapsChunkSize: 2000 // default 1000
},
})
网站地图的前缀
您会注意到,默认情况下,所有多站点地图都出现在/__sitemap__/前缀下。如果你想改变这一点,你可以使用sitemapsPathPrefix选项,并将站点地图键更改为你想要的名称。
export default defineNuxtConfig({
sitemap: {
sitemapsPathPrefix: '/', // or false
sitemaps: {
// will be available at /sitemap-foo.xml
['sitemap-foo']: {
// ...
}
}
}
})
手动组块
当手动分块站点地图时,根据您的需要有多种处理方法。
无论哪种情况,如果您希望在站点地图中为url提供默认值,您都可以使用defaults选项。
defaults -站点地图默认值,如lastmod、changefreq或priority
export default defineNuxtConfig({
sitemap: {
sitemaps: {
posts: {
// posts low priority
defaults: { priority: 0.7 },
},
},
},
})
扩展应用程序源
当你的单一站点地图包含所有正确的url,你只是想把它们分割成单独的站点地图,你可以扩展应用程序源和过滤url。
includeAppSources -使用应用程序源
includeGlobalSources -使用全局资源
include -包含在站点地图中的全局模式数组
exclude -要从站点地图中排除的全局模式数组
示例 nuxt.config.ts
export default defineNuxtConfig({
sitemap: {
sitemaps: {
pages: {
// extend the nuxt:pages app source
includeAppSources: true,
// filter the URLs to only include pages
exclude: ['/blog/**'],
},
posts: {
// extend the nuxt:pages app source
includeAppSources: true,
// filter the URLs to only include pages
include: ['/blog/**'],
},
},
},
})
如果你使用的是全局站点地图。源并需要进一步过滤url,那么您可以使用_sitemap键。
_sitemap - URL应该包含在其中的站点地图的名称
示例 nuxt.config.ts
export default defineNuxtConfig({
sitemap: {
sources: [
'/api/sitemap-urls'
],
sitemaps: {
pages: {
includeGlobalSources: true,
includeAppSources: true,
exclude: ['/**']
// ...
},
},
},
})
示例 server/api/sitemap-urls.ts
export default defineSitemapEventHandler(() => {
return [
{
loc: '/about-us',
// will end up in the pages sitemap
_sitemap: 'pages',
}
]
})
管理资源
如果您需要从站点地图的端点获取url,那么您将需要使用url或sources选项。
urls -包含在站点地图中的静态url数组。如果您有很多url,则应避免使用此选项
sources——自定义端点,以JSON或XML的形式获取动态url。
export default defineNuxtConfig({
sitemap: {
sitemaps: {
posts: {
urls() {
// resolved when the sitemap is shown
return ['/foo', '/bar']
},
sources: [
'/api/sitemap-urls'
]
},
},
},
})
链接外部站点地图
这种模式还提供了一个称为index的特殊键,它允许您轻松地扩展索引站点地图。这对于添加外部站点地图很有用。
export default defineNuxtConfig({
sitemaps: {
// generated sitemaps
posts: {
// ...
},
pages: {
// ...
},
// extending the index sitemap with an external sitemap
index: [
{ sitemap: 'https://www.google.com/sitemap-pages.xml' }
]
}
})
自动分块
这将使用0-sitemap.xml, 1-sitemap.xml命名约定自动将站点地图分成多个站点地图。
它将在defaultSitemapsChunkSize选项上进行分块,默认为每个站点地图1000个url。
如果url少于1000个,应该避免使用这种方法。
示例
export default defineNuxtConfig({
sitemap: {
// automatically chunk into multiple sitemaps
sitemaps: true,
},
})
Images, Videos, News
学习如何在站点地图中添加图像、视频和新闻。
介绍
默认情况下,图像、视频和新闻名称空间被添加到您的站点地图中,允许您为站点地图条目配置图像、视频和新闻。
当预渲染应用程序时,生成的站点地图可能会自动从页面中推断出图像和视频。
网站地图图像
要向站点地图添加图像,可以使用站点地图条目上的images属性。
您可以在谷歌文档(Google documentation)中了解更多关于站点地图中的图像的信息。
示例
export interface ImageEntry {
loc: string
}
你可以这样实现:
示例 nuxt.config.ts
export default defineNuxtConfig({
sitemap: {
urls: [
{
loc: '/blog/my-post',
images: [
{
loc: 'https://example.com/image.jpg',
caption: 'My image caption',
geoLocation: 'My image geo location',
title: 'My image title',
license: 'My image license',
}
]
}
]
}
})
自动图像发现
该模块可以发现您的页面中的图像,并将它们自动添加到您的站点地图。
要做到这一点:
页面必须预先呈现。这些图像将不会在开发中显示,或者如果页面没有预呈现。
你必须用<main>标签包装你的页面内容,避免包装包含重复图像的共享布局。
视频
要向站点地图添加视频,可以使用站点地图条目上的视频属性。
视频的TypeScript接口如下:
示例
export interface VideoEntry {
title: string
thumbnail_loc: string | URL
description: string
content_loc?: string | URL
player_loc?: string | URL
duration?: number
expiration_date?: Date | string
rating?: number
view_count?: number
publication_date?: Date | string
family_friendly?: 'yes' | 'no' | boolean
restriction?: Restriction
platform?: Platform
price?: ({
price?: number | string
currency?: string
type?: 'rent' | 'purchase' | 'package' | 'subscription'
})[]
requires_subscription?: 'yes' | 'no' | boolean
uploader?: {
uploader: string
info?: string | URL
}
live?: 'yes' | 'no' | boolean
tag?: string | string[]
}
您可以在谷歌文档( Google documentation)中了解更多关于站点地图中的视频的信息。
你可以这样实现:
示例 nuxt.config.ts
export default defineNuxtConfig({
sitemap: {
urls: [
{
loc: '/blog/my-post',
videos: [
{
title: 'My video title',
thumbnail_loc: 'https://example.com/video.jpg',
description: 'My video description',
content_loc: 'https://example.com/video.mp4',
player_loc: 'https://example.com/video.mp4',
duration: 600,
expiration_date: '2021-01-01',
rating: 4.2,
view_count: 1000,
publication_date: '2021-01-01',
family_friendly: true,
restriction: {
relationship: 'allow',
country: 'US',
},
platform: {
relationship: 'allow',
platform: 'web',
date: '2021-01-01',
},
price: [
{
price: 1.99,
currency: 'USD',
type: 'rent',
}
],
requires_subscription: true,
uploader: {
uploader: 'My video uploader',
info: 'https://example.com/uploader',
},
live: true,
tag: ['tag1', 'tag2'],
}
]
}
]
}
})
自动视频发现
与自动图像发现一样,您可以选择在<main>标记中包含视频标记的自动视频发现。
您还需要为视频提供标题和描述,这可以使用data-title和data-description属性来完成。
示例 simple
<video
controls
poster="https://archive.org/download/DuckAndCover_185/__ia_thumb.jpg"
width="620"
data-title="Duck and Cover"
data-description="This film, a combination of animated cartoon and live action, shows young children what to do in case of an atomic attack."
>
<source
src="https://archive.org/download/DuckAndCover_185/CivilDefenseFilm-DuckAndCoverColdWarNuclearPropaganda_512kb.mp4"
type="video/mp4"
/>
<source
src="https://archive.org/download/DuckAndCover_185/CivilDefenseFilm-DuckAndCoverColdWarNuclearPropaganda.avi"
type="video/x-msvideo"
/>
Sorry, your browser doesn't support embedded videos. However, you can
<a href="https://archive.org/details/DuckAndCover_185">download it</a>
and watch it with your favorite video player!
</video>
示例 full
<video
controls
poster="https://archive.org/download/DuckAndCover_185/__ia_thumb.jpg"
width="620"
data-title="Duck and Cover"
data-description="This film, a combination of animated cartoon and live action, shows young children what to do in case of an atomic attack."
data-rating="4.2"
data-view-count="1000"
data-publication-date="2021-01-01"
data-family-friendly="yes"
>
每种格式都将以以下格式添加到站点地图中:
示例
<video:video>
<video:thumbnail_loc>https://archive.org/download/DuckAndCover_185/__ia_thumb.jpg</video:thumbnail_loc>
<video:title>Duck and Cover</video:title>
<video:description>
This film, a combination of animated cartoon and live action, shows young children what to do in case of an atomic attack.
</video:description>
<video:content_loc>
https://archive.org/download/DuckAndCover_185/CivilDefenseFilm-DuckAndCoverColdWarNuclearPropaganda_512kb.mp4
</video:content_loc>
</video:video>
新闻
要向站点地图添加新闻,可以使用站点地图条目上的news属性。只支持谷歌的新闻站点地图(Google's News sitemap)扩展。
新闻的TypeScript接口如下:
示例
export interface GoogleNewsEntry {
title: string
publication_date: Date | string
publication: {
name: string
language: string
}
}
你可以这样实现:
示例 nuxt.config.ts
export default defineNuxtConfig({
sitemap: {
urls: [
{
loc: '/news/nuxt-sitemap-turns-6',
news: [
{
title: 'Nuxt Sitemap Turns 6',
publication_date: '2021-01-01',
publication: {
name: 'Nuxt Sitemap',
language: 'en',
},
}
]
}
]
}
})
图像和视频选择退出
要选择退出这种行为,您可以将discoverImages和discoverVideos配置分别设置为false。
export default defineNuxtConfig({
sitemap: {
discoverImages: false,
discoverVideos: false,
}
})
二.全站规则 - Robots
简介
在/robots.txt目录下生成robots.txt文件。
将附加一个<meta name="robots" content="<rule>">和一个X-Robots HTTP报头。
如果您有除开发和生产之外的任何其他环境,则需要配置env选项。有关详细信息,请参阅禁用索引指南。
缺省情况下,允许所有user-agent的所有路由。请参阅禁用页面索引以开始阻止路由。
快速安装
推荐nuxt安装
npx nuxi module add robots
其他命令安装
npm i @nuxtjs/robots
#
yarn add @nuxtjs/robots
#
pnpm i @nuxtjs/robots
#
bun i @nuxtjs/robots
其他安装配置
其他命令安装需要手动配置文件 nuxt.config.ts
export default defineNuxtConfig({
modules: [
'@nuxtjs/robots',
],
})
实践应用
介绍
obots.txt文件位于您的根目录中,是控制爬虫如何访问您的站点的常用方法。
✅适用于:
阻塞较大的站点部分(例如/admin/*)
管理重型页面上的爬虫带宽(例如,搜索、无限滚动)
防止爬行开发站点
❌不要用于:
保护敏感数据(爬虫程序可以忽略规则)
个人页面索引(使用元机器人代替)
从搜索结果中删除现有页面
实现robots.txt很简单,您可以为Vue / next应用程序创建静态文件或动态文件。
快速设置
要快速开始使用静态robots.txt,请将该文件添加到公共目录中:
示例
public/
robots.txt
添加你的规则:
示例 robots.txt
# Allow all crawlers
User-agent: *
Disallow:
# Optionally point to your sitemap
Sitemap: https://mysite.com/sitemap.xml
动态实现
在某些情况下,您可能更喜欢动态robots.txt文件。也就是说,我们在服务器端根据环境或其他因素生成文件。
示例 vue
// example using Vite SSR
function createServer() {
const app = express()
// ..
app.get('/robots.txt', (req, res) => {
const robots = `
User-agent: *
Disallow: /admin
`
res.type('text/plain').send(robots)
})
// ..
}
示例 nuxt
import { getRequestHost } from 'h3'
// server/routes/robots.txt.ts
export default defineEventHandler((e) => {
const host = getRequestHost(e)
return host.includes('staging')
? 'User-agent: *\nDisallow: /'
: 'User-agent: *\nDisallow:'
})
next Robots模块可以自动处理此操作。
解析robots.txt
robots.txt文件由以下主要指令组成:
示例 robots.txt
# Define which crawler these rules apply to
User-agent: *
# Block access to specific paths
Disallow: /admin
# Allow access to specific paths (optional)
Allow: /admin/public
# Point to your sitemap
Sitemap: https://mysite.com/sitemap.xml
用户代理
User-agent指令指定规则应用于哪个爬虫:
示例 robots.txt
# All crawlers
User-agent: *
# Just Googlebot
User-agent: Googlebot
# Multiple specific crawlers
User-agent: Googlebot
User-agent: Bingbot
Disallo