3.0 KiB
3.0 KiB
Micro URL Shortener
A tiny URL shortener in a single PHP file (index.php). It needs no database: links are stored in plain text files.
How it works
urls.txt: one link per line, written as<key> <url>.last.txt: the most recently issued key. Each new key is made by incrementing it over a shuffled character set (a,c,r, … thenaa,ac, …).- Visiting
/<key>sends a 301 redirect to the stored URL, or returns 404 if the key is unknown. - Visiting
/shows a mobile-friendly form for shortening a URL.
Requirements
- PHP 7+ with the
mbstringextension. - The web server must be able to write
urls.txtandlast.txtin the app directory. - Every request path must be routed to
index.php(see below).
Setup
- Copy
index.phpto your web root. - Edit the configuration at the top of the file. At minimum, change
$password. - Route all requests to
index.php.
Apache (.htaccess):
RewriteEngine On
RewriteRule ^(urls|last)\.txt$ - [F]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
nginx:
location ~ ^/(urls|last)\.txt$ { deny all; }
location / { try_files $uri /index.php?$query_string; }
Local development (PHP's built-in server, using index.php as the router):
php -S localhost:4000 index.php
Block direct access to
urls.txtandlast.txt(as in the rules above). Otherwise anyone can download your whole link list.
Configuration
| Variable | Default | Purpose |
|---|---|---|
$password |
'change me!' |
Required to shorten a URL. Set to '' to disable (not recommended). |
$allowed_domains |
[] |
Domains allowed as link targets. An empty list allows any domain. |
$max_url_length |
100 |
Longer URLs are rejected. |
$charset |
(shuffled) | Characters used in keys. Don't change it once links exist. |
$enable_test |
false |
Turns on the key-generation test form. |
$urls_file, $last_file |
urls.txt, last.txt |
Where the data is stored. |
API
Shorten a URL from the command line. The response is plain text:
curl --data-urlencode 'url=https://example.com/page' \
--data-urlencode 'password=your-password' \
https://your-host/
# https://your-host/c
| Status | Meaning |
|---|---|
| 200 | Success; body is the short URL |
| 401 | Wrong or missing password |
| 403 | Domain not allowed |
| 422 | Invalid or overlong URL |
GET parameters work too (/?url=...&password=...), but they put the password in server logs and browser history, so prefer POST.
Short URLs always start with https:// followed by the request's host.