Skip to content

Instantly share code, notes, and snippets.

@matthew-brett
Created July 19, 2015 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthew-brett/5c93800e19a36b7e5de1 to your computer and use it in GitHub Desktop.
Save matthew-brett/5c93800e19a36b7e5de1 to your computer and use it in GitHub Desktop.
""" Make html pages redirecting to another URL base
USAGE: rewrite_pages.py <path-to-html> <base-url-to-redirect-to>
"""
import os
from os.path import join as pjoin, relpath
import sys
REDIRECT_TEMPLATE="""\
<!-- Redirect the user to {0}-->
<meta http-equiv="refresh" content="0; url={0}">
<!-- Specify that {0} is the canonical URL -->
<link rel="canonical" href="{0}" />
"""
def write_redirects(root_path, url_root):
for dirpath, dirnames, filenames in os.walk(root_path):
for filename in filenames:
if not filename.endswith('.html'):
continue
full_path = pjoin(dirpath, filename)
rel_path = relpath(full_path, root_path)
if rel_path.startswith('.'):
rel_path = rel_path[1:]
url = '{}/{}'.format(url_root, rel_path)
with open(full_path, 'wt') as fobj:
fobj.write(REDIRECT_TEMPLATE.format(url))
def main():
write_redirects(sys.argv[1], sys.argv[2])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment