Absolute URLs in RSS Feeds

Hey!

I’ve looked through the forum and searched online but there doesn’t seem to be a solution within Hugo for this: RSS feeds must have absolute URLs inside their description tags. Relative URLs must not be used since there’s no way in the RSS specification to set the URL base.

For the users using relative URLs on their Hugo posts, is there a way to force absolute URLs only on certain layouts? In this case on the RSS layout?

I created a script to post-process every .xml file and update the URLs, but I’d prefer a solution within Hugo.

Thanks

To solve this I ended up using a hyper complex partial to replace all URLs by absolute ones in the .Content variable on feeds:

{{ $html := htmlUnescape .Content | safeHTML }}

{{ $hrefs := findRE "href=\"([^\"]*)\"" $html }}
{{ range $href := $hrefs}}
  {{ $absHref := strings.TrimPrefix "href=\"" $href  }}
  {{ $absHref = strings.TrimSuffix "\"" $absHref  }}
  {{ $absHref = printf "href=\"%s\"" ($absHref | absURL) }}
  {{ $html = replace $html $href $absHref }}
{{ end }}

{{ $srcs := findRE "src=\"([^\"]*)\"" $html }}
{{ range $src := $srcs}}
  {{ $absSrc := strings.TrimPrefix "src=\"" $src  }}
  {{ $absSrc = strings.TrimSuffix "\"" $absSrc  }}
  {{ $absSrc = printf "src=\"%s\"" ($absSrc | absURL) }}
  {{ $html = replace $html $src $absSrc }}
{{ end }}

{{ $srcset := findRE "srcset=\"([^\"]*)\"" $html }}
{{ range $set := $srcset}}
  {{ $parts := strings.TrimPrefix "srcset=\"" $set  }}
  {{ $parts = strings.TrimSuffix "\"" $parts  }}
  {{ $parts = split $parts "," }}
  {{ $newSrcset := slice }}
  {{ range $part := $parts }}
    {{ $part = $part | replaceRE "^\\s*(.*)\\s*$" "$1" }}
    {{ $lg := split $part " " }}
    {{ $href := index $lg 0 | absURL }}
    {{ $size := index $lg 1 }}
    {{ $newSrcset = $newSrcset | append (printf "%s %s" $href $size) }}
  {{ end }}
  {{ $newSrcset = delimit $newSrcset ", " }}
  {{ $newSrcset = printf "srcset=\"%s\"" $newSrcset }}
  {{ $html = replace $html $set $newSrcset }}
{{ end }}

{{ return $html }}
2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.