跳到主要内容

防盗链

Nginx 防盗链

# 静态资源服务
# 访问路径 C:/bolawen/Assets
location ^~ /Assets{
root C:/bolawen/;
# 访问白名单: bolawen.com bolawen.cn localhost 用空格分隔
valid_referers bolawen.cn bolawen.com localhost;
# refer 为空或者不在白名单,直接指向 404
if ($invalid_referer) {
return 404;
}
}

Koa 防盗链

:::details config.js

exports.allowReferer=['bolawen.cn','bolawen.com','localhost'];
exports.repositoryList={
Blog:"../Blog",
Assets:"../Assets",
"bolawen.github.io":'../bolawen.github.io',
}

:::

:::details app.js

const fs = require("fs");
const Koa = require("koa");
const koaBody = require("koa-body");

const app = new Koa();

app.use(koaBody({ multipart: true }));

const routerList = fs
.readdirSync("./router/")
.map((item) => require("./router/" + item));
routerList.forEach(item=>{
app.use(item.routes());
});

app.listen(4000, function () {
console.log("服务启动成功!");
});

:::

:::details router>image.js

const fs=require('fs');
const path=require('path');
const Router=require('koa-router');
const antiStealingLink=require('../middleware/antiStealingLink');

const router=Router({prefix:'/image'});
const dirPath=join('../../Assets/images/bg');
const fileList=fs.readdirSync(dirPath);


function join(pathArgs){
return path.join(__dirname,pathArgs)
}
function getOneOfList(){
const imageTotal=fileList.length;
return Math.floor(Math.random()*(imageTotal-0+1))+0;
}
function getIndexOfTotal(index,total){
const imageTotal=fileList.length;
const groupTotal=Math.floor(imageTotal/total);
const restTotal=imageTotal%total;
const rangeStart=index*groupTotal;
let rangeEnd=rangeStart+groupTotal-1;
if(index+1==total){
rangeEnd=rangeEnd+restTotal;
}
return Math.floor(Math.random()*(rangeEnd-rangeStart+1))+rangeStart;
}

router.get('/bg',antiStealingLink,async (ctx)=>{
ctx.set('Content-Type','image/jpg');
const imageName=getOneOfList();
const imageFile=fs.readFileSync(dirPath+"/"+imageName+'.jpg');
ctx.body=imageFile;
})
router.get('/one',antiStealingLink,async (ctx)=>{
ctx.set('Content-Type','image/jpg');
const {index,total}=ctx.request.query;
const imageName=getIndexOfTotal(index,total);
const imageFile=fs.readFileSync(dirPath+"/"+imageName+'.jpg');
ctx.body=imageFile;
});
module.exports=router;

:::

:::details middleware>antiStealingLink.js

const fs=require('fs');
const path=require('path');
const {allowReferer} =require('../config');

const dirPath=join('../../Assets/images/');
const file=fs.readFileSync(dirPath+'404.png');

function join(pathArgs){
return path.join(__dirname,pathArgs)
}

module.exports=async (ctx,next)=>{
const referer=ctx.request.header.referer;
if(!referer){
ctx.set('Content-Type','image/jpg');
ctx.body=file;
return
}
const result=allowReferer.some(value=>{
return referer.includes(value)==true;
});
if(!result){
ctx.set('Content-Type','image/jpg');
ctx.body=file;
return
}
next();
}

:::