通过 Nginx 与 Cloudflare Workers 反向代理常见服务(Github、Telegram)
Github
Nginx
TIP
使用 1Panel 的还需要将 Nginx 自带配置中的 proxy_set_header Host $host;
注释掉
nginx
location /robots.txt {
allow all;
}
location / {
valid_referers none blocked raw.githubusercontent.com github.com;
if ($invalid_referer) {
return 403;
}
proxy_hide_header content-security-policy;
proxy_hide_header Strict-Transport-Security;
proxy_hide_header set-cookie;
proxy_hide_header x-pjax-url;
proxy_set_header Host raw.githubusercontent.com;
proxy_http_version 1.1;
proxy_connect_timeout 5s;
proxy_read_timeout 5s;
proxy_pass https://raw.githubusercontent.com;
}
Cloudflare Workers
js
const hostname = 'api.telegram.org';
addEventListener('fetch', (event) => {
let url = new URL(event.request.url);
url.hostname = hostname;
url.protocol = 'https';
let request = new Request(url, event.request);
event.respondWith(fetch(request));
});
Telegram
Nginx
TIP
使用 1Panel 的还需要将 Nginx 自带配置中的 proxy_set_header Host $host;
注释掉
前缀匹配
nginx
location ^~ /bot {
resolver 8.8.8.8;
proxy_buffering off;
proxy_pass https://api.telegram.org$request_uri;
}
正则匹配
nginx
location ~* ^/bot {
resolver 8.8.8.8;
proxy_buffering off;
proxy_pass https://api.telegram.org$request_uri;
}
Cloudflare Workers
基础版
js
const hostname = 'api.telegram.org';
addEventListener('fetch', (event) => {
let url = new URL(event.request.url);
url.hostname = hostname;
url.protocol = 'https';
let request = new Request(url, event.request);
event.respondWith(fetch(request));
});
进阶版
- 为了防止被滥用,我们希望反代的 API 只有自己的机器人可以使用,因此还可以对请求的链接进行判断
- 在 whitelist 中填入自己的机器人 ID
js
const whitelist = '/botXXXXXXXXXX:';
const hostname = 'api.telegram.org';
addEventListener('fetch', (event) => {
let url = new URL(event.request.url);
url.hostname = hostname;
url.protocol = 'https';
if (!url.pathname.startsWith(whitelist)) {
return new Response('Unauthorized', {
status: 403
});
}
let request = new Request(url, event.request);
event.respondWith(fetch(request));
});
通用反代
使用方式:访问 https://domain.com/yourpath/https://raw.githubusercontent.com/
js
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
const url = new URL(request.url);
if (!url.pathname.startsWith('/yourpath/')) {
return new Response('Not Found', { status: 404 });
}
const actualUrlStr = url.pathname.replace('/yourpath/', '') + url.search + url.hash;
const actualUrl = new URL(actualUrlStr, url.origin);
const modifiedRequest = new Request(actualUrl, {
headers: request.headers,
method: request.method,
body: request.body,
redirect: 'follow'
});
const response = await fetch(modifiedRequest);
const modifiedResponse = new Response(response.body, response);
modifiedResponse.headers.set('Access-Control-Allow-Origin', '*');
return modifiedResponse;
}
预览: