今天偶然发现博客的好多外链没有rel标签,这会使得SEO权重外流!

然后我想,不仅仅是友链页,我想要让全站的外链都加上rel="noopener noreferrer nofollow"
,包括一些图片。
并且要智能判断是不是本站链接,如果是本站链接就不加
而且如果href属性包含JavaScript代码(如javascript:void(0);
),这种情况不应视为外部链接。
而且,为了确保都能加上,不管原来有没有rel标签或者rel标签是否正确,不管是否有target,都全部替换rel=”noopener noreferrer nofollow”
我想到了一种方法,通过 Hexo 的 after_render
过滤器,无需修改主题文件即可为全站外链动态添加 rel
属性。这样不修改主题文件也确保了稳定性。
于是学习了下hexo的文档并且请教了一下deepseek,写出了这些代码,经过测试是可以正常使用的。
解决方法
在 Hexo 博客根目录下创建 /scripts/add-rel.js
文件,如果没有/scripts
文件夹请你自行创建
它会获取_config.yml的url段,url字段你必须要填对
在/scripts
文件夹下的js文件会自动被Hexo执行,不需要手动引入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| const { URL } = require('url');
hexo.extend.filter.register('after_render:html', function (htmlContent) { const siteUrl = new URL(hexo.config.url).origin;
const regex = /<a\s+([^>]*)>/gi;
return htmlContent.replace(regex, (match, attributes) => { const attrMap = {}; attributes.replace(/(\w+)\s*=\s*(["'])(.*?)\2/gi, (_, key, quote, value) => { attrMap[key] = value; return ''; });
const href = attrMap.href;
let isExternal = false; try { if (href && !href.startsWith('javascript:') && !href.startsWith('#')) { const url = new URL(href, siteUrl); isExternal = url.origin !== siteUrl; } } catch (e) { console.warn(`Invalid URL: ${href}`); }
if (isExternal) { attrMap.rel = 'noopener noreferrer nofollow'; }
const newAttributes = Object.keys(attrMap) .map(key => `${key}="${attrMap[key]}"`) .join(' ');
return `<a ${newAttributes}>`; }); });
|
之后执行Hexo三件套

可以看到,rel标签出现了!