Creating a cross-platform url file

Posted: 17 Feb 2025. Last modified on 18-Feb-25.

This article will take about 2 minutes to read.



Can a URL exist as a file?

Yes it can! Depending on your platform you might be familiar with these file types, which when clicked, open the given URL in a browser window

So it is possible natively, but often can be difficult to work with in practice. I’ve always wanted to have an easy, cross-platform way to do this.

It turns out this is possible with modern web standards! No matter which system, we can always count on HTML.

If you define an html document like this

<meta http-equiv="Refresh" content="0; url='https://google.com'" />

it will open up as a normal html file, then perform a redirect. The destination in this case would be https://google.com

Next steps?

Taking this one step further, I wrote a script which will allow regular URLs to be mapped into their respective URL files. It would be run like

% python3 create-url-file.py 'https://google.com' 

and produce a file like

google.com.html

The code

If you would like the script, here it is.

Note that if a portion of the url is not safe for use in a filename, it will just be replaced with a double underscore, __.

import sys
import re
import os

def sanitize_filename(url: str) -> str:
    # Remove the scheme (http, https) and replace non-filename characters with '__'
    sanitized = re.sub(r'[^a-zA-Z0-9.-]', '__', url.replace('https://', '').replace('http://', ''))
    return sanitized + ".html"

def generate_meta_redirect(url: str):
    meta_tag = f'<meta http-equiv="Refresh" content="0; url=\'{url}\'" />\n'
    filename = sanitize_filename(url)
    
    with open(filename, 'w') as f:
        f.write(meta_tag)
    
    print(f"Meta redirect written to {filename}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python3 script.py <URL>")
        sys.exit(1)
    
    url = sys.argv[1]
    generate_meta_redirect(url)