本文将指导你使用 Cloudflare WorkersWorkers KV 构建一个功能完整的短链接跳转服务,具备以下特性:

  • ✅ 支持创建短链接(如 /abc123 跳转到目标 URL)
  • ✅ 自动检测微信浏览器并拦截访问
  • ✅ 在微信中打开时显示友好提示:“请复制到浏览器打开”
  • ✅ 使用 Cloudflare KV 存储映射关系(免费额度足够个人使用)
  • ✅ 提供 Web 界面用于生成短链
  • ✅ 防止重复提交相同长链接(基于 SHA-1 哈希去重)
  • ✅ 阻止用户输入自身短链接(避免循环)
  • ✅ 友好的 404 页面与错误提示

✅ 第一步:准备工作

  1. 注册 Cloudflare 账号
  2. 进入 Workers & Pages → 创建一个新 Worker(例如命名为 url-shortener
  3. 在该 Worker 的 Settings → Variables → KV Namespace Bindings 中:
    • 点击 Create a namespace
    • 命名空间名称建议为:URL_MAPPINGS
  4. 将命名空间绑定到 Worker:
    • Variable name: LINKS
    • KV namespace: 选择刚创建的 URL_MAPPINGS

⚠️ 注意:代码中使用的是 LINKS 作为 KV 绑定变量名,请确保一致。


✅ 第二步:部署 Worker 代码

将以下完整 JavaScript 代码粘贴到你的 Worker 编辑器中,并保存部署。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
// === 配置区 ===
const SHORT_CODE_LENGTH = 6;

// === 新增:404友好提示页面 ===
const NOT_FOUND_PAGE = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>短链接不存在</title>
<style>
body {
background: #121212;
color: #f0f0f0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
padding: 20px;
overflow: hidden;
}
.container {
background: #252526;
border-radius: 12px;
padding: 30px;
max-width: 500px;
width: 100%;
box-shadow: 0 4px 20px rgba(0,0,0,0.5);
text-align: center;
}
.error-icon {
font-size: 48px;
margin-bottom: 15px;
color: #f44336;
}
h1 {
color: #fff;
margin-bottom: 20px;
}
p {
margin-bottom: 25px;
color: #e0e0e0;
}
.btn {
background: #0078d4;
color: white;
border: none;
border-radius: 8px;
padding: 12px 24px;
font-size: 16px;
cursor: pointer;
transition: background 0.2s;
}
.btn:hover {
background: #0066b3;
}
</style>
</head>
<body>
<div class="container">
<div class="error-icon">❌</div>
<h1>短链接不存在</h1>
<p>您访问的短链接已失效或不存在</p>
<button class="btn" onclick="window.location.href='/'">返回主页</button>
</div>
</body>
</html>
`;

const WECHAT_BLOCK_PAGE = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>提示</title>
<style>
body {
background: #121212;
color: #f0f0f0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.card {
background: #252526;
border-radius: 12px;
padding: 30px;
width: 90%;
max-width: 400px;
text-align: center;
box-shadow: 0 4px 20px rgba(0,0,0,0.5);
}
h2 {
margin: 0 0 20px;
font-size: 20px;
color: #ff6b6b;
}
p {
margin: 8px 0;
line-height: 1.6;
font-size: 16px;
}
.highlight {
color: #4da6ff;
font-weight: bold;
}
</style>
</head>
<body>
<div class="card">
<h2>⚠️无法在当前应用中打开</h2>
<p>点击右上角菜单</p>
<p>选择 <span class="highlight">“在浏览器中打开”</span></p>
</div>
</body>
</html>
`;

// === 工具函数 ===
function isBannedUA(ua) {
ua = ua.toLowerCase();
return /micromessenger/i.test(ua) || /weibo/.test(ua) || /qq\//.test(ua);
}

async function sha1(str) {
const encoder = new TextEncoder();
const data = encoder.encode(str);
const hashBuffer = await crypto.subtle.digest('SHA-1', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

function generateShortCode() {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let result = '';
for (let i = 0; i < SHORT_CODE_LENGTH; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}

// === 主页 HTML(含表单)===
const homePage = () => `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>短链接生成器</title>
<style>
- { scrollbar-width: thin; scrollbar-color: #bdc3c7 #ecf0f1; }
body {
background: #121212;
color: #f0f0f0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
margin: 0; padding: 150px 0 0 0;
display: flex; flex-direction: column; align-items: center;
min-height: 100vh; position: relative; overflow: hidden;
}
body::before {
content: ""; position: fixed; left: 0; top: 0; z-index: 0;
width: 100%; height: 100%;
background: url(https://www.loliapi.com/acg/pe/) #fff;
background-position: right center;
background-size: auto 100%;
background-attachment: fixed;
opacity: 0.5;
}
.container {
display: flex; flex-direction: column; justify-content: center; align-items: center;
position: relative; z-index: 1; width: 100%;
padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto;
}
h1 { font-size: 24px; margin-bottom: 30px; color: #ffffff; }
.card {
background: #252526; border-radius: 12px; padding: 24px;
width: 90%; max-width: 1000px; box-shadow: 0 4px 20px rgba(0,0,0,0.5);
}
input[type="url"] {
width: 100%; padding: 12px 16px; background: #1e1e1e;
border: 1px solid #333; border-radius: 8px; color: #fff;
font-size: 16px; box-sizing: border-box; outline: none;
}
input[type="url"]:focus { border-color: #4da6ff; }
button {
width: 100%; padding: 12px; background: #0078d4; color: white;
border: none; border-radius: 8px; font-size: 16px; margin-top: 16px;
cursor: pointer; transition: background 0.2s;
}
button:hover { background: #0066b3; }
.result {
margin-top: 20px; padding: 14px; background: #1e1e1e;
border-radius: 8px; word-break: break-all; font-size: 15px;
display: flex; flex-direction: column; gap: 10px;
}
.result.success { color: #4caf50; }
.result.error { color: #f44336; }
a { color: #4da6ff; text-decoration: none; }
a:hover { text-decoration: underline; }
.copy-btn {
align-self: flex-start; background: #4da6ff; color: #000;
border: none; border-radius: 6px; padding: 6px 12px;
font-size: 14px; cursor: pointer; transition: opacity 0.2s;
}
.copy-btn:hover { opacity: 0.9; }
.copy-feedback {
font-size: 14px; color: #4caf50; height: 18px; margin-top: 4px;
}
.links {
position: fixed; bottom: 0; z-index: 99999; width: 100%;
margin-bottom: 0; padding: 5px 10px; text-align: center;
background-color: #00000088; color: #fff;
}
.links a { color: #eee; text-decoration: none; }
.links a:hover { color: #fff; text-decoration: underline; }
</style>
</head>
<body>
<div class="container">
<h1>🔗 短链接生成器</h1>
<div class="card">
<form id="shorten-form">
<input type="url" id="url-input" placeholder="请输入完整网址(如 https://example.com)" required />
<button type="submit">生成短链接</button>
</form>
<div class="result"></div>
</div>
<p class="links">友链:
<a href="https://m3u8.xuehuayu.cn" target="_blank">M3U8去广告播放器</a> |
<a href="https://chrome.xuehuayu.cn" target="_blank">Chrome命令行参数生成器</a> |
<a href="https://laonongmin.online" target="_blank">免费影视APP</a> |
<a href="https://chromewebstore.google.com/search/KK%20Player" target="_blank">免费影视扩展</a> |
<a href="https://jc.zzmy.dpdns.org/" target="_blank">便宜机场</a>
</p>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('shorten-form');

// 事件委托处理复制按钮
document.addEventListener('click', (e) => {
if (e.target.classList.contains('copy-btn')) {
const shortUrl = e.target.closest('.result').querySelector('a').href;
copyLink(shortUrl);
}
});

form.addEventListener('submit', async (e) => {
e.preventDefault();

// 客户端微信检测(双重保险)
if (/MicroMessenger/i.test(navigator.userAgent)) {
alert('请在浏览器中打开,不要在微信中使用');
return;
}

const urlInput = document.getElementById('url-input');
const url = urlInput.value.trim();
if (!url) return alert('请输入网址');

const button = form.querySelector('button');
const originalText = button.textContent;
button.textContent = '生成中...';
button.disabled = true;

try {
const response = await fetch('/', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ url })
});

const result = await response.text();
const resultDiv = document.querySelector('.result');

if (result.startsWith('http')) {
resultDiv.innerHTML = \`
<div class="result success">
✅ 生成成功!<br>
<a href="\${result}" target="_blank">\${result}</a>
<button class="copy-btn">📋 复制链接</button>
<div class="copy-feedback" id="copy-feedback"></div>
</div>
\`;
} else {
resultDiv.innerHTML = \`<div class="result error">\${result}</div>\`;
}
urlInput.value = '';
} catch (err) {
alert('网络错误,请重试');
} finally {
button.textContent = originalText;
button.disabled = false;
}
});

async function copyLink(text) {
try {
await navigator.clipboard.writeText(text);
document.getElementById('copy-feedback').innerText = '✅ 已复制到剪贴板!';
} catch (err) {
const tempInput = document.createElement('input');
tempInput.value = text;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand('copy');
document.body.removeChild(tempInput);
document.getElementById('copy-feedback').innerText = '✅ 已复制(请手动粘贴)';
}
setTimeout(() => {
document.getElementById('copy-feedback').innerText = '';
}, 2000);
}
});
</script>
</body>
</html>
`;

// === 请求处理器 ===
async function handleRequest(request) {
const url = new URL(request.url);
const path = url.pathname;
const userAgent = request.headers.get('User-Agent') || '';
const inWechat = isBannedUA(userAgent);

// 1. 微信环境拦截(所有路径)
if (inWechat) {
return new Response(WECHAT_BLOCK_PAGE, {
headers: { 'Content-Type': 'text/html; charset=utf-8' }
});
}

// 2. 处理短链接跳转(格式:/xxxxxx)
const shortCodeMatch = path.match(/^\/([a-zA-Z0-9]{6})$/);
if (shortCodeMatch) {
const shortCode = shortCodeMatch[1];
const targetUrl = await LINKS.get(shortCode);
if (targetUrl) {
return Response.redirect(targetUrl, 302);
} else {
return new Response(NOT_FOUND_PAGE, {
headers: { 'Content-Type': 'text/html; charset=utf-8' }
});
}
}

// 3. GET / → 返回主页
if (request.method === 'GET' && path === '/') {
return new Response(homePage(), {
headers: { 'Content-Type': 'text/html; charset=utf-8' }
});
}

// 4. POST / → 生成短链
if (request.method === 'POST' && path === '/') {
try {
const formData = await request.formData();
let targetUrl = formData.get('url')?.trim();

if (!targetUrl) throw new Error('请输入网址');

// 补全协议
if (!/^https?:\/\//i.test(targetUrl)) {
targetUrl = 'https://' + targetUrl;
}

// 规范化:移除末尾斜杠
const normalizedUrl = targetUrl.replace(/\/$/, '');

// 防止输入自身短链接
try {
const inputUrl = new URL(normalizedUrl);
const currentDomain = new URL(url.origin);
if (
inputUrl.hostname === currentDomain.hostname &&
inputUrl.pathname.length === 7 &&
/^[a-zA-Z0-9]{6}$/.test(inputUrl.pathname.substring(1))
) {
return new Response('输入的URL是短链接,请输入长链接', {
headers: { 'Content-Type': 'text/plain; charset=utf-8' }
});
}
} catch (e) {
throw new Error('网址格式无效');
}

// 哈希去重
const urlHash = (await sha1(normalizedUrl)).substring(0, 12);
const hashKey = `hash:${urlHash}`;
const existingCode = await LINKS.get(hashKey);

if (existingCode) {
return new Response(`${url.origin}/${existingCode}`, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' }
});
}

// 生成新短码
const shortCode = generateShortCode();
await Promise.all([
LINKS.put(shortCode, normalizedUrl),
LINKS.put(hashKey, shortCode)
]);

return new Response(`${url.origin}/${shortCode}`, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' }
});

} catch (e) {
console.error('短链生成失败:', e.message);
return new Response(`❌ ${e.message}`, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
status: 400
});
}
}

// 5. 其他路径 → 404
return new Response(NOT_FOUND_PAGE, {
headers: { 'Content-Type': 'text/html; charset=utf-8' }
});
}

// === Cloudflare Workers 入口 ===
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});


✅ 功能说明

功能 实现方式
短链生成 POST / 提交 url 参数,返回 https://your-worker.example/abc123
跳转 访问 /abc123 → 302 重定向到原始 URL
微信拦截 检测 UA 中包含 MicroMessengerweiboQQ/,返回提示页
防重复 对规范化 URL 计算 SHA-1 哈希前 12 位,存为 hash:xxx,下次直接返回已有短码
防自环 禁止用户提交形如 https://your-worker.example/xxxxxx 的短链接
404 页面 所有无效路径均返回友好提示

🛡️ 安全与隐私说明

  • 本服务 不收集任何用户数据
  • 不使用 Cookie、LocalStorage(除临时复制外)
  • 所有逻辑运行在 Cloudflare 边缘节点
  • KV 存储仅包含:短码 → 长链接哈希 → 短码 映射

🔧 后续可扩展方向

  • 添加 API Key 验证(防止滥用)
  • 支持自定义短码(如 /github
  • 添加点击统计(需额外 KV 或 D1)
  • 集成密码保护短链
  • 支持批量生成

💡 提示:此方案完全免费(Cloudflare Workers 免费计划支持每日 10 万次请求 + 1GB KV 存储),适合个人或小团队使用。


✅ 现在,访问你的 Worker URL(如 https://url-shortener.yourname.workers.dev),即可开始使用!