Hugo Tips & Tricks: How to exclude some contents from the sitemap

How to deal with sitemap in Hugo? Well, you don’t need to do anything, Hugo will generate a complete sitemap for you during the build. That’s cool. But what if you wanted to change the structure or remove some pages?

The problem

In the image below you will notice that the same content was indexed twice, once in the post page and once in the list of all articles about node.

tag-page-in-serp.png

Ok this is not cool at all. Even worst, when a blog is updated infrequently the list of posts could be considered the main content and the post not be indexed at all!

The solution might be to create your own sitemap (see how to do that in the Hugo doc), but then you would have to do tedious manual work every time you publish a new post.

Sitemap manipulation

A good solution is to exclude the list pages from the sitemap. To customize the sitemap you need to override the following file in your theme: layouts/_default/sitemap.xml.

In this example I included only post pages and home pages (The condition if or (.IsPage) (.IsHome) does the job):

{{ printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>" | safeHTML }}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 
        xmlns:xhtml="http://www.w3.org/1999/xhtml">
  {{ range .Data.Pages }}
    {{ if or (.IsPage) (.IsHome) }}
    <url>
        <loc>{{ .Permalink }}</loc>
        {{ if not .Lastmod.IsZero }}
            <lastmod>{{ safeHTML ( .Lastmod.Format "2006-01-02T15:04:05-07:00" ) }}</lastmod>
        {{ end }}
        {{ with .Sitemap.ChangeFreq }}
            <changefreq>{{ . }}</changefreq>
        {{ end }}
        {{ if ge .Sitemap.Priority 0.0 }}
            <priority>{{ .Sitemap.Priority }}</priority>
        {{ end }}
        {{ if .IsTranslated }}
        {{ range .Translations }}
        <xhtml:link
                rel="alternate"
                hreflang="{{ .Language.LanguageCode }}"
                href="{{ .Permalink }}"
        />
        {{ end }}
        <xhtml:link
                rel="alternate"
                hreflang="{{ .Language.LanguageCode }}"
                href="{{ .Permalink }}"
        />
        {{ end }}
    </url>
    {{ end }}
  {{ end }}
</urlset>

layouts/_default/sitemap.xml

shining.jpg The Shining, Stanley Kubrick 1980

Irene Iaccio

Freelance web developer

Subscribe to the monthly digest!

I'll use your email only to send you the latest posts once a month.