Iâve recently been looking for a way to automatically rel=ânofollowâ my outbound links in Jekyll, so that theyâre SEO-friendly and I can add some custom styling to them.
There were a fair few plugins that would do the job, which I managed to figure out with some trial and error. However, since Iâm using GitHub Pages to build and publish my site, I could either change my workflow (build locally, publish the built site) or find a way to do this using only supported plugins. In the end, I figured out how to do it without plugins at all!
Jekyllâs built in Liquid templating has a replace filter, which is perfect for the job.
How to do it:
This assumes youâre using standard Markdown for your off-site links, in the format [link text](http://link.com)
, and relative internal links, in the format [link text](/local/link)
- Locate your default.html layout
- _It should be in layouts
- Look for a variable for the page content, like this
{{content}}
- Replace it with either:
{{ content | replace: '<a href="http', '<a rel="nofollow noopener noreferrer" href="http' }}
- Or, if you want to open off-site links in a new tab
{{ content | replace: '<a href="http', '<a rel="nofollow noopener noreferrer" target="_blank" href="http' }}
- Save, build and test
How it works
As long as youâre using standard Markdown links, all of your off-site links will look like this:
<a href="http...
And your internal links like this:
<a href="/...
The filter above takes the content of your website, as Jekyll produces it, and replaces the search string <a href="http
with the same, but with rel=ânofollowâ before it.
Update: thanks to Ashish in the comments for providing the security additions of noopener
and noreferrer
.
Itâs pretty simple, and pretty dumb. You may need to troubleshoot if your setup is different (e.g. single instead of double quotes), and it wonât work if you link to your local site with absolute links. However, it will work for most scenarios, including https links (because it just takes up to and including the âpâ).
Give it a whirl, see if it works. Let me know below if you get into trouble.
Jamie