I want to built some short urls for uploaded files and links on my own server. Simple enough, I upload files and my script returns me a link. On access, the link is translated to the file and download starts. Because it's modern, I want my links short and not so UUID4-like, because they are very long.
I do not want that someone tries a few URLs to found a valid link. Maybe I should sent only 404's if an IP already had 10 wrong urls called?
To built short random strings I thinking about the following:
- Prefill a SQL-Table
(key, target)
wherekey
is case sensitive with all possible values in a defined range like[a-zA-Z0-9_-~=]{12}
. Then select withWHERE target IS NULL ORDER BY RANDOM()
an empty key and use it. This will guarantee I never generate the same key twice but needs a lot of storage and may be too much. - I generate an UUID4-string and throw an hash-algorithm like SHA3 over it and use the first 12 characters of the result. Then I try to insert this in my table. If this fails, I need to generate an new UUID4 and so on...
Of course, these are very theoretical thoughts, because I think I will be fine with 1000 keys per year. But how shortening url services do this? Or they don't care about "unpredictableness"?