迁移语雀文章图片访问403

原本想把语雀上的一部分内容迁移到自己的 Blog 上,语雀也提供了把文章转为 makrdown 的功能。
转出来的文章的图片是存在语雀 cdn 的链接。

后续操作过来,发现图片无法显示,图片请求报 403 错误。

1
2
3
4
5
Request URL: XXX
Request Method: GET
Status Code: 403
Remote Address: 58.216.16.42:443
Referrer Policy: strict-origin-when-cross-origin

但本地直接访问 html 文件的话,图片链接是可以直接访问的。
对比了一下俩边的请求头,发现可能是 refrrer 参数值的缘故。

1
referer: http://localhost:4000/

通过在 img 添加 referrer 策略 <img referrerpolicy="no-referrer">
去处图片请求带 referer 参数,发现访问成功。

说明语雀在服务端检测到图片访问来源不是 yuque.com 时,会拒接访问。
为了一劳永逸,每次去改这个值也不是个事。

hexo 的主题里面可以通过添加一个 filter 正则处理 img 的添加内联参数。
会在每次文章渲染后,去做一次正则替换。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
'use strict'
hexo.extend.filter.register(
'after_post_render',
function (data) {
const theme = hexo.theme.config;
if (!theme.no_referrer) return;
data.content = data.content.replace(
// Match 'img' tags width the src attribute.
/<img([^>]*)src="([^"]*)"([^>\/]*)\/?\s*>/gim,
function (match, attrBegin, src, attrEnd) {
// Exit if the src doesn't exists.
if (!src) return match;
return `<img referrerpolicy="no-referrer"
src="${src}"
>`
}
)
},
1
);

Bingo,完美解决问题,让语雀充当了个免费的 cdn。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!