How does nuxt generate sitemap.xml dynamic and static site map

foreword

The function of sitemap.xml is to include all the pages of our website by SEO (browser search engine), the content of our website is easier to be searched by users, and at the same time, it increases the popularity of our website and ranks higher. In short, it is to use technology to promote the website, so the technology of website promotion sitemap is still very important. The implementation process is a bit cumbersome, but it is not difficult. Let’s start today’s tutorial.

Operating procedures

1. Installation dependencies

npm install @nuxtjs/sitemap

This link is the official documentation of sitemap on npm

2. Open nuxt.config.js and add its dependencies to represent our entire project using this dependency

注意:之前引入的依赖不用删,只需要将sitemap加在后面

{
    
    
  modules: [
    '@nuxtjs/sitemap'
  ],
}

3. Enter the static folder, create sitemap.js, the content is as follows

1. Explanation of each configuration item
import axios from "axios";  // 引入axios,动态生成站点地图需要用到
const sitemap = {
    
    
  path: "/sitemap.xml", //生成的文件路径
  hostname: "http://www.baidu.com/", // 你的网站地址
  cacheTime: 1000 * 60 * 60 * 24, //一天的更新频率,只在generate:false有用
  gzip: true, //用gzip压缩优化生成的 sitemap.xml  文件 
  generate: false, 
  exclude: [], //排除不需要收录的页面,这里的路径是相对于hostname, 例如: exclude: ['/404',...]
  // 每个对象代表一个页面,这是默认的
  defaults: {
    
    
    changefred: "always", // 收录变化的时间,always 一直,daily 每天
    lastmod: new Date(), // 生成该页面站点地图时的时间
    priority: 1, // 网页的权重  1是100%最高,一般给最重要的页面,不重要的页面0.7-0.9之间
  },
  routes: async () => {
    
    
    return routes
  },
};
export default sitemap;
2. Generate static code

这里主要放那种不需要携带的页面,示例: http://www.baidu.com/pressCenter,每个对象的url的前缀是自动相对上面hostname网站地址的,所以只需要写你的路由就行。

 routes: async () => {
    
    
    // 静态路由
    let routes = [
      {
    
    
        url: `/`,
        changefred: "daily",
        lastmod: new Date(),
        priority: 1,
      },
      {
    
    
        url: `/pressCenter`,
        changefred: "daily",
        lastmod: new Date(),
        priority: 0.9,
      },
    ];
    return routes
   }
3. Generate dynamic code

动态指的是类似详情页这种 http://www.baidu.com/detail?id=1 ,这种是根据后端数据自动生成的,不可能手动一个一个去加,那样就太机械了,不符合我们写程序的风格,所以这一小节就是讲如何生成动态站点地图。

    let axiosUrl = "你的接口请求前缀";  // 示例 "http://www.baidu.cn/api/"
    let prodRoutes = [];
    let newsRoutes = [];

    // Promist.all并发调接口  所有异步接口同时调用,缩短生成站点地图的时间,通过解构取出接口返回的数据
    let [productList, newsList] = await Promise.all([
      axios.get(axiosUrl + "product/list"),
      axios.get(axiosUrl + "news/list"),
    ]);
   
    // 商品详情   
    /* 200状态码判断这块属于代码优化  成功才进来,否则之间打印错误信息,由于nuxt有时出问题能提供给我们的信息非常匮乏,
    	假设某天接口出问题,到时很难定位问题,所以加这个主要是方便我们后期的维护。  */
    if (productList.data.code == 200) {
    
    
      let proList = productList.data.rows; // 这个对应接口返回的列表
      // 用map将列表里的每个对象的id组装同时生成新的对象,每个对象生成后的样子,见下面标注1
      prodRoutes = proList.map((item) => {
    
    
        return {
    
    
          url: `/product/twoPage/threePage?id=${
      
      item.id}`,
          changefred: "daily",
          lastmod: new Date(),
          priority: 1,
        };
      });
    } else {
    
    
      console.log(productList.data.msg, "sitemap调用错误+productList");
    }

    // 文章详情
    if (newsList.data.code == 200) {
    
    
      let newsArr = newsList.data.rows;
      newsRoutes = newsArr.map((item) => {
    
    
        return {
    
    
          url: `/pressCenter/article?id=${
      
      item.id}`,
          changefred: "daily",
          lastmod: new Date(),
          priority: 1,
        };
      });
    } else {
    
    
      console.log(newsList.data.msg, "sitemap调用错误+newsList");
    }
    // 最后统一将所有组装好的数组合并到总数组中,记住传入合并的数组顺序要跟Promise.all调用接口的顺序一致,否则会出问题
    // 合并后的样子 见下面标注2
    return routes.concat(prodRoutes, newsRoutes);

标注1

// 示例:某一路由对象生成后的样子
   	   {
    
    
         url: `/pressCenter/article?id=1`,
         changefred: "daily",
         lastmod: new Date(),
         priority: 1,
       }

标注2
routes.concat is an array merging method, we can use it to merge static and dynamic site objects into a routing array, and the sitemap will eventually use this array to process it into real sitemap.xml data

[
    {
    
    
       url: `/`,
       changefred: "daily",
       lastmod: new Date(),
       priority: 1,
   },
   {
    
    
       url: `/product/twoPage/threePage?id=1`,
       changefred: "daily",
       lastmod: new Date(),
       priority: 1,
   },
   {
    
    
       url: `/pressCenter/article?id=1`,
       changefred: "daily",
       lastmod: new Date(),
       priority: 1,
   },
   ...
]

4. Introduce and use the sitemap.js configuration file globally in nuxt.config.js

// nuxt.config.js
import sitemap from "./static/sitemap";
// sitemap跟modules是同级的,一般放在modules的上面或者下面
 modules: [
    "@nuxtjs/sitemap"
  ],
sitemap: sitemap,

5. Complete code of sitemap.js

import axios from "axios";  //
const sitemap = {
    
    
  path: "/sitemap.xml", //生成的文件路径
  hostname: "http://www.baidu.com/", //网站的网址
  cacheTime: 1000 * 60 * 60 * 24, //一天的更新频率,只在generate:false有用
  gzip: true, //用gzip压缩优化生成的 sitemap.xml  文件 
  generate: false,
  exclude: [], //排除不要的页面,这里的路径是相对于hostname
  defaults: {
    
    
    changefred: "always",
    lastmod: new Date(),
  },
  routes: async () => {
    
    
    // 静态路由
    let routes = [
      {
    
    
        url: `/`,
        changefred: "daily",
        lastmod: new Date(),
        priority: 1,
      },
      {
    
    
        url: `/pressCenter`,
        changefred: "daily",
        lastmod: new Date(),
        priority: 0.9,
      },
    ];

    // 以下都是动态路由
    let axiosUrl = "你的接口请求前缀";  // 示例 "http://www.baidu.com/api/"
    let prodRoutes = [];
    let newsRoutes = [];

    // 并发调接口
    let [productList, newsList] = await Promise.all([
      axios.get(axiosUrl + "product/list"),
      axios.get(axiosUrl + "news/list"),
    ]);

    // 商品详情
    if (productList.data.code == 200) {
    
    
      let proList = productList.data.rows;
      prodRoutes = proList.map((item) => {
    
    
        return {
    
    
          url: `/product/twoPage/threePage?id=${
      
      item.id}`,
          changefred: "daily",
          lastmod: new Date(),
          priority: 1,
        };
      });
    } else {
    
    
      console.log(productList.data.msg, "sitemap调用错误+productList");
    }

    // 文章详情
    if (newsList.data.code == 200) {
    
    
      let newsArr = newsList.data.rows;
      newsRoutes = newsArr.map((item) => {
    
    
        return {
    
    
          url: `/pressCenter/article?id=${
      
      item.id}`,
          changefred: "daily",
          lastmod: new Date(),
          priority: 1,
        };
      });
    } else {
    
    
      console.log(newsList.data.msg, "sitemap调用错误+newsList");
    }

    return routes.concat(prodRoutes, newsRoutes);
  },
};
export default sitemap;

6. How to generate sitemap.xml file

1. Start the nuxt project
  • Open the static -> robots.txt file. If there is no robots.txt file, I will enter the tutorial and add two Sitemap attributes, a local project address and an online address. When generating the sitemap.xml file, you need to comment out the online address with the # sign, and then put the local link such as http://192.168.1.193/sitemap.xml in the browser to visit, 193 corresponds to your host ip.
User-agent: *
Disallow:
# Sitemap: http://www.baidu.com/sitemap.xml
Sitemap: http://192.168.1.193/sitemap.xml
2. It looks like this after accessing, and then CTRL + S to save sitemap.xml to the desktop, so far the steps of sitemap.xml generation are over.

<loc>标签中的网站地址是根据sitemap.js中的hostname设置的值
insert image description here

3. After the generation is complete, change the sitemap of robots.txt to an online address
User-agent: *
Disallow:
Sitemap: http://www.baidu.com/sitemap.xml
# Sitemap: http://192.168.1.193/sitemap.xml
4. Nuxt front-end npm run build:prod makes a package to the back-end

7. How to upload sitemap.xml to the server

这里以服务器Nginx为例

1. Upload here

insert image description here

2. Configure the access path of sitemap.xml in the Nginx configuration file

insert image description here
After configuring Nginx reload, reload it, and then open the webpage your URL/sitemap.xml to see if you can access it. If you can, it means that your website has been successfully included by Baidu.

8. Digression

This article has just been written recently, and some typos or certain sentence expressions will be corrected in the follow-up.

Guess you like

Origin blog.csdn.net/Steven_Son/article/details/127922593