文件服务器防盗链,在Ghost博客的nginx服务器上部署防盗链

折腾了一晚上,终于搞定了。搜索了很久都没有搜到有相关的中文文章,甚至英文的都很少,全是generic的nginx部署防盗链的文章,特此总结整理一下方便以后查询。

想必nginx防盗链的部署方法大家都知道了,在装了Ghost的情况下稍稍有所不同,主要因为实际访问的文件不在根目录下,而是在ghost的安装目录中,所以要用到proxy。就因为这一点折腾了好久,症状就是加入防盗链代码后所有图片自动404,加了proxy之后就好了。

以下是我使用的代码:

location /content/ { valid_referers none blocked ~.google. ~.bing. ~.baidu. server_names ~($host); if ($invalid_referer) { rewrite ^/ http://ww1.sinaimg.cn/large/76b129b3gy1fisvu3x79lj21hc0u0ta2.jpg; } try_files $uri @ghost; } location @ghost { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:2368; }

代码解释如下:

location /content/

↑因为ghost的特殊性,所有上传的图片都在content目录下,如有需求还是改成扫描文件后缀。

valid_referers none blocked ~.google. ~.bing. ~.baidu. server_names ~($host);

↑关于valid_referers网上的解释很多了,推荐阅读 官网的定义(https://nginx.org/en/docs/http/ngx_http_referer_module.html) 。包含了几个搜索引擎,当然不希望图片被搜索引擎爬的也可以去掉,后面使用了host变量方便大家直接复制黏贴。

if ($invalid_referer)

↑当来源没有列在上述列表中,$invalid_refererfan返回值为1,执行rewrite。

rewrite ^/ http://ww1.sinaimg.cn/large/76b129b3gy1fisvu3x79lj21hc0u0ta2.jpg;

↑rewrite到一个外部图床的防盗链图片,注意用自己的图片网址替换我的网址,如果不需要,可直接 return 444。

try_files $uri @ghost;

↑最重要的一步,因为实际访问的文件并不在服务器的root directory下,本身ghost-cli自动部署的nginx配置就带proxy。try_files的定义请看官方文档。

location @ghost { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:2368; }

↑这里我照抄了ghost-cli部署时写入的proxy代码。

写入conf之后重启nginx即可。

注:由于本站强制https访问,所以在http段直接设置了所有访问content都rewrite到盗链图片上:

location /content/ { rewrite ^/ http://ww1.sinaimg.cn/large/76b129b3gy1fisvu3x79lj21hc0u0ta2.jpg; }

原文出处:mcfly -> https://mcfly.cn/ghost-blog-hotlink-protection-with-nginx-server/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值