[nginx/openresty]代理请求修改referer,破解防盗链

/ 191,030评论 / 526531阅读 / 17点赞

有时我们想引用其他网站的资源(图片,视频等),明明在其网站上可用,而我们发送请求时却得到了403错误,访问被拒绝,很可能就是该网站对这些资源文件设置了防盗链,下面我们聊聊其防盗的原理以及破解方法。

名词

防盗链

Referer

Origin

破解防盗链

直接伪造请求

这个方法适用于客户端,而不适用于浏览器中的网页。

const axios = require(`axios`);
const getServer = (in_url, in_data, successFun, errFun) => {
    axios({
        method: "get",
        url:    in_url,
        params: in_data,
        headers: {
            "referer":"https://www.bilibili.com/"

            //"referer":"https://127.0.0.1/"  //你可以尝试使用这一句替换上面那句,请求将被拒绝
        }
    }).then(function (res) {
        console.log(res.data);
        if (typeof (successFun) != 'undefined') {
            successFun(res);
        }
        console.log("--- 请求成功 ---");
    }).catch(function (err) {
        console.log(err);
        if (typeof (errFun) != 'undefined') {
            errFun(err);
        }
        console.log("--- 请求失败 ---");
    })
}

//获取对应id的视频的下载链接
getServer(
    "https://api.bilibili.com/x/player/playurl",
    {
        "fnval": 80,
        "bvid":"BV1pT41157it",
        "cid":"746904707"
    });

代理转发

客户端,网页都适用,但一般客户端不需要由服务器代理,客户端自己可以搞定,就不需要占用服务器的带宽性能

server {
        listen       80;
        server_name  localhost, 127.0.0.1;
	resolver 8.8.8.8;
        location / {
		header_filter_by_lua_file /usr/local/openresty/lua/toBili.lua;
                proxy_set_header referer 'https://www.bilibili.com/';
		proxy_set_header Host $proxy_host;
		proxy_set_header Origin 'https://www.bilibili.com';
		if ($query_string ~* ^(.*)url=(.*)$) {
			proxy_pass $2;
		}
	}
}
ngx.header['Access-Control-Allow-Origin']  =  '*';
ngx.header['Access-Control-Allow-Methods'] = 'get, post, options';
ngx.header['Access-Control-Allow-Headers'] = 'dnt,x-mx-reqtoken,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,authorization';

关于空referer

<!DOCTYPE html>
<html lang="zh">
<head>

    <meta name="referrer" content="never">
</head>
<body>
</body>

摸索过程记录

add_header Access-Control-Allow-Origin '*';
add_header Access-Control-Allow-Methods 'POST,OPTIONS,GET';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

思考

上面的示例中,我们在使用时,只能也必须传入一个参数 url,那有没有办法传递更多参数呢?

  1. ShawnArede说道:

    Новини України https://sensus.org.ua та світу сьогодні. Головні та останні новини дня

  2. JeromeZef说道:

    Головні новини https://mediashare.com.ua про регіон України. Будьте в курсі останніх новин

  3. Derekexall说道:

    Новини та аналітика https://newsportal.kyiv.ua ситуація в Україні.

  4. Richardson说道:

    Головні новини https://pto-kyiv.com.ua України та світу

  5. JoshuaRef说道:

    Україна останні новини https://lentanews.kyiv.ua головні новини та останні події

  6. Davidanymn说道:

    Свіжі новини України https://lenta.kyiv.ua останні новини з-за кордону, новини політики, економіки, спорту, культури.

  7. Stephenlep说道:

    Популярные репортажи https://infotolium.com в больших фотографиях, новости, события в мире

  8. KennethAgrip说道:

    Україна свіжі новини https://kiev-pravda.kiev.ua останні події на сьогодні

  9. EddieFer说道:

    Новини України https://kiev-online.com.ua останні події в Україні та світі сьогодні, новини України за минулий день онлайн

  10. Sal说道:

    Nice blog! Is your theme custom made or did you download it from somewhere?
    A theme like yours with a few simple adjustements would really make my blog stand out.
    Please let me know where you got your theme.
    Cheers

  11. Jamesvaf说道:

    Останні новини України https://gromrady.org.ua сьогодні онлайн – головні події світу

  12. Great website. Plenty of useful information here.

    I am sending it to a few friends ans additionally sharing in delicious.
    And naturally, thank you for your sweat!

  13. HarrySwice说道:

    Новинний ресурс https://actualnews.kyiv.ua про всі важливі події в Україні та світі.

  14. RobertArith说道:

    Новини сьогодні https://gau.org.ua останні новини України та світу онлайн

  15. BrandonSaili说道:

    продвижение бизнеса в интернете под ключ seo продвижение сайта

  16. Rogerrip说道:

    The Story Concerning Solana Creator Toly Yakovenko’s Achievement
    Following A Couple of Mugs of Coffees and a Ale
    Yakovenko, the brainchild behind Solana, started his venture with an ordinary practice – coffee and beer. Unbeknownst to him, these occasions would trigger the wheels of his future. Currently, Solana stands as a powerful player in the crypto realm, featuring a billion-dollar market value.

    Initial Ethereum ETF Sales
    The recently launched Ethereum ETF newly started with a huge trading volume. This landmark occasion experienced multiple spot Ethereum ETFs from different issuers be listed in the U.S., introducing unprecedented activity into the usually calm ETF trading environment.

    SEC’s Approval of Ethereum ETF
    The U.S. SEC has given the nod to the Ethereum exchange-traded fund for being listed. As a cryptographic asset with smart contracts, Ethereum is expected to significantly impact on the cryptocurrency industry with this approval.

    Trump’s Crypto Maneuver
    With the election nearing, Trump positions himself as the ‘Crypto President,’ continually showcasing his backing of the blockchain space to attract voters. His strategy contrasts with Biden’s strategy, intending to capture the attention of the cryptocurrency community.

    Elon Musk’s Influence
    Elon, a prominent figure in the blockchain world and an advocate of Trump’s agenda, caused a stir again, boosting a meme coin related to his antics. His involvement keeps influencing the market landscape.

    Binance Updates
    A subsidiary of Binance, BAM, is now permitted to allocate customer funds in U.S. Treasury securities. Additionally, Binance celebrated its 7th year, emphasizing its journey and securing numerous regulatory approvals. Simultaneously, Binance also made plans to delist several major crypto trading pairs, impacting various market participants.

    AI and Market Trends
    Goldman Sachs’ top stock analyst recently mentioned that AI won’t spark an economic transformation

  17. оборудование для проведения конференций oborudovanie-konferenc-zalov.ru .

  18. jydoll说道:

    Other consumers love using photographs エロ 人形with their silicone love dolls.

  19. StevenVes说道:

    seo продвижение сайты топ 10 заказать сео продвижение

  20. Danielcaw说道:

    заказать продвижение корпоративного сайта создание и раскрутка сайта

  21. Stephenbot说道:

    Помощь студентам в выполнении рефератов https://referatkupit-oline.ru. Низкие цены и быстрое написание рефератов!

  22. RichardSut说道:

    Красивая музыка https://melodia.space для души слушать онлайн.

  23. Охраняйте свою конфиденциальность с резидентскими прокси, как это работает.
    Обходите географические блокировки с резидентскими прокси, широким контентом.
    Оптимизируйте работу сети благодаря резидентским прокси, в чем преимущество.
    Обезопасьте свои онлайн-платежи с резидентскими прокси, и не беспокойтесь о своей безопасности.
    Защитите свою личную жизнь и данные с резидентскими прокси, и наслаждайтесь анонимностью.
    Скачивайте файлы анонимно через резидентские прокси, и не бойтесь за свою приватность.
    резидентские прокси https://rezidentnie-proksi.ru/ .

  24. CharlesUsalf说道:

    Заказать курсовую работу https://kursovye-napishem.ru в Москве: цены на написание и выполнение, недорого

  25. DavidSiz说道:

    Заказать дипломную работу https://diplomzakazat-oline.ru недорого. Дипломные работы на заказ с гарантией.

  26. Rogercrurl说道:

    купить двухкомнатную в новостройке https://kvartira-novostroyka2.ru

  27. Johnnydit说道:

    Заказать контрольную работу https://kontrolnye-reshim.ru, недорого, цены. Решение контрольных работ на заказ срочно.

  28. ThomasHow说道:

    Помощь в решении задач https://zadachireshaem-online.ru. Опытные авторы с профессиональной подготовкой окажут консультацию в решении задач на заказ недорого, быстро, качественно

  29. Chante说道:

    I have been browsing online greater than 3 hours today, but I
    never discovered any interesting article like yours.
    It’s beautiful value sufficient for me. Personally, if all webmasters and bloggers made excellent content as
    you probably did, the web might be a lot more
    useful than ever before.

  30. Raymondfup说道:

    купить квартиру в новостройке цены квартиры от застройщика

  31. Tommieduh说道:

    купить двухкомнатную квартиру в новостройке https://kvartira-novostroi.ru

  32. JacobSteax说道:

    Discover your perfect stay with WorldHotels-in.com, your ultimate destination for finding the best hotels worldwide! Our user-friendly platform offers a vast selection of accommodations to suit every traveler’s needs and budget. Whether you’re planning a luxurious getaway or a budget-friendly adventure, we’ve got you covered with our extensive database of hotels across the globe. Our intuitive search features allow you to filter results based on location, amenities, price range, and guest ratings, ensuring you find the ideal match for your trip. We pride ourselves on providing up-to-date information and competitive prices, often beating other booking sites. Our detailed hotel descriptions, high-quality photos, and authentic guest reviews give you a comprehensive view of each property before you book. Plus, our secure booking system and excellent customer support team ensure a smooth and worry-free experience from start to finish. Don’t waste time jumping between multiple websites – http://www.WorldHotels-in.com brings the world’s best hotels to your fingertips in one convenient place. Start planning your next unforgettable journey today and experience the difference with WorldHotels-in.com!

  33. BrandonAdumn说道:

    The Hidden Story Regarding Solana Founder Toly’s Accomplishment
    After Two Servings of Java and a Beer
    Yakovenko, the innovator behind Solana, began his venture with a simple routine – two coffees and a brew. Little did he know, these instances would trigger the machinery of his destiny. Today, Solana remains as a significant competitor in the blockchain realm, having a billion-dollar market value.

    Initial Ethereum ETF Sales
    The Ethereum ETF lately was introduced with an impressive trade volume. This landmark occasion witnessed various spot Ethereum ETFs from different issuers commence trading on U.S. exchanges, bringing extraordinary activity into the typically calm ETF trading environment.

    SEC Sanctions Ethereum ETF
    The U.S. SEC has formally approved the spot Ethereum ETF to trade. As a crypto asset with smart contracts, it is expected that Ethereum to have a profound impact the crypto industry with this approval.

    Trump’s Bitcoin Tactics
    With the upcoming election, Trump positions himself as the ‘Crypto President,’ frequently displaying his advocacy for the cryptocurrency industry to garner votes. His approach is different from Biden’s approach, targeting the attention of the blockchain community.

    Elon Musk’s Impact
    Musk, a notable figure in the crypto community and a proponent of Trump, shook things up once again, driving a meme coin associated with his antics. His involvement continues to shape the market environment.

    Recent Binance News
    A subsidiary of Binance, BAM, has been allowed to channel customer funds in U.S. Treasuries. Additionally, Binance celebrated its 7th year, emphasizing its development and acquiring several compliance licenses. In the meantime, the company also announced plans to delist several notable cryptocurrency trading pairs, impacting various market participants.

    AI and Market Trends
    Goldman Sachs’ top stock analyst recently mentioned that AI won’t spark a major economic changeHere’s the spintax version of the provided text with possible synonyms

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注