October 29 2021
Jekyll Tip: Absolute URLs for Links and Images in RSS Feed
When I write a post and add an image, the image lives in the “files” folder. When Jekyll builds the static site locally, I can see the image inline. When I push the site to GitHub Pages, I can see the image online in the post with my web browser. But when I view the feed in an RSS reader (Reeder for me), no image.
The issue is the URL for the image is a relative path instead of an absolute path:
# Relative Path
/files/example.jpg
# Absolute Path
https://bdunagan.com/files/example.jpg
The RSS reader doesn’t know what the base path is. But if I wrote it with the absolute URL format locally, I couldn’t see it until I pushed the post live.
Web browsers handle relative URLs, but RSS readers are not consistent about it. You can add “xml:base” to your feed, but there is no guarantee that the RSS reader will observe it.
Below is a quick Jekyll hack to replace relative URLs for links and images with absolute URLs in /feed.xml
, using Liquid’s replace
method:
{{ post.content | replace: 'src="/', 'src="https://bdunagan.com/' }}
Here is the code in the context of my entire feed.xml
file:
---
layout: null
---
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>{{ site.title }}</title>
<description>{{ site.description }}</description>
<link>{{ site.url }}</link>
<atom:link href="{{ site.url }}/feed.xml" rel="self" type="application/rss+xml" />
{% for post in site.posts limit:20 %}
<item>
<title>{{ post.title }}</title>
<description>{{ post.content | xml_escape | replace: 'javascript||' | replace: 'shell||' | replace: 'ruby||' | replace: 'html||' | replace: 'src="/', 'src="https://bdunagan.com/' | replace: 'href="/', 'href="https://bdunagan.com/' }}</description>
<pubDate>{{ post.date | date: "%a, %d %b %Y %H:%M:%S %z" }}</pubDate>
<link>{{ site.url }}{{ post.url }}</link>
<guid isPermaLink="true">{{ site.url }}{{ post.url }}</guid>
</item>
{% endfor %}
</channel>
</rss>
By replacing the relative links to absolute links in the RSS feed, the post is viewable in development and in production as well as in an RSS reader, without any modifications.