Sometimes you need to execlude uneeded links from rendering to the sitemap.xml in hugo. Here is a quick guide of how to do that.

Understanding the Problem

By default, Hugo generates a sitemap that includes all the pages of your website. However, there are cases where you might want to exclude certain pages from this sitemap. This could include thank you pages, landing pages, or any content not meant for public consumption.

The Solution

Hugo offers a flexible system for managing page metadata through front matter, which makes excluding pages from the sitemap a breeze. Here’s a step-by-step guide on how to do it:

1. Modify Front Matter

In the content files of the pages you want to exclude, add a custom parameter called sitemap_exclude and set it to true:

  ---
title: "Page Title"
date: 2023-05-26
sitemap_exclude: true
---
  

2. Update the Sitemap Template

Next, you’ll need to modify your sitemap template to respect the sitemap_exclude parameter. Locate or create the sitemap.xml template in your Hugo project and update it as follows:

  {{- /* Filter pages to exclude those with sitemap_exclude set to true */ -}}
{{- $pages := where .Site.RegularPages "Params.sitemap_exclude" "!=" true -}}

{{- printf "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" | safeHTML -}}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  {{- range $pages -}}
  <url>
    <loc>{{ .Permalink }}</loc>
    <lastmod>{{ .Date.Format "2006-01-02" }}</lastmod>
    {{ with .Params.changefreq }}<changefreq>{{ . }}</changefreq>{{ end }}
    {{ with .Params.priority }}<priority>{{ . }}</priority>{{ end }}
  </url>
  {{- end -}}
</urlset>
  

3. Rebuild Your Site

Finally, rebuild your Hugo site to apply these changes. Your sitemap will now exclude pages with sitemap_exclude: true in their front matter.

Conclusion

Managing your website’s sitemap is an essential aspect of SEO and ensuring a smooth user experience. With Hugo’s flexibility and powerful templating system, excluding specific pages from your sitemap is a straightforward process. By leveraging custom front matter parameters and updating your sitemap template, you can tailor your sitemap to include only the content you want to be indexed by search engines.