GitHub-Powered Short URL System: Zero Server Cost
Build a scalable short URL service using GitHub's infrastructure. This guide shows how to use commit hashes as keys and Git tags for readable URLs.
Core Mechanism
- Commit Hash → Short code (7 characters)
- Commit Message → Stores target URL
- GitHub Pages → Handles redirection
- Git Tags → Create human-readable links
Implementation Steps
1. Base Setup
Create a GitHub repository named short-url
and enable GitHub Pages in settings.
2. Redirection Page
Create index.html
:
<!DOCTYPE html>
<html>
<script>
(async () => {
const path = window.location.pathname.slice(1);
const apiUrl = `https://api.github.com/repos/yourname/short-url/commits/${path}`;
try {
const res = await fetch(apiUrl);
if (!res.ok) throw new Error();
const data = await res.json();
window.location.href = data.commit.message.split('\n')[0];
} catch {
document.body.innerHTML = '🔗 Broken link';
}
})();
</script>
<body>Redirecting...</body>
</html>
3. Generate Short Links
Method 1: Commit Hash
git commit --allow-empty -m "https://your-long-url.com"
git push
SHORT_CODE=$(git rev-parse HEAD | cut -c1-7)
echo "Short URL: https://yourname.github.io/short-url/$SHORT_CODE"
Method 2: Semantic Tags
git tag newsletter-link
git push origin newsletter-link
# Access via: https://yourname.github.io/short-url/newsletter-link
Optimization Tips
1. Local Caching
Add to script:
const cached = localStorage.getItem(path);
if (cached) window.location.href = cached;
else {
// After API call
localStorage.setItem(path, url);
}
2. Handle Rate Limits
Use GitHub token:
fetch(apiUrl, {
headers: { 'Authorization': 'token YOUR_TOKEN' }
})
3. Automation Script
Create generate-url.sh
:
#!/bin/bash
git commit --allow-empty -m "$1"
git push
SHORT=$(git rev-parse HEAD | cut -c1-7)
echo "https://yourname.github.io/short-url/$SHORT"
if [ -n "$2" ]; then
git tag $2
git push origin $2
fi
Key Considerations
- Public History: All URLs appear in git logs
- Rate Limits: 60 API calls/hour (unauthorized)
- Collision Risk: 7-character hash works for small systems
Why This Works:
GitHub serves as free infrastructure. Commit hashes provide unique IDs. Pages handle traffic. Tags enable memorable links.
Maintenance:
Edit URLs via git commit --amend
. Delete bad links with git rebase
.
Top comments (0)