Need to bulk-create .htaccess redirects? This will pull in a CSV file with your old & new paths (don't include the domain) and correctly format the redirects based on if the old path contains dynamic URLs
Code:
import csv
import re
def main():
# Instantiate Other Variables
input_path = str(raw_input("Input CSV File Path: "))
output_path = open(str(raw_input("Output Text File Path: ")), "wt")
url_list = list(csv.reader(open(input_path, 'r')))
headers = url_list[0]
del url_list[0]
# Walk through the list and write to the file
for line in url_list:
removed_leading_slash = line[0].lstrip('/')
separated_dynamic_variable_part = re.search('(?<=\?)([^\s]+)', removed_leading_slash)
separated_dynamic_variable_before = re.search('([^\s]+)(?=\?)', removed_leading_slash)
# Determine if a URL is dynamic and apply appropriate formatting
if separated_dynamic_variable_part and separated_dynamic_variable_before:
string = 'RewriteCond %{{QUERY_STRING}} ^{0}$ [NC]\nRewriteRule ^{1}$ {2}? [R=301,L]\n'
output_path.write(string.format(separated_dynamic_variable_part.group(), separated_dynamic_variable_before.group(), line[1]))
else:
output_path.write("RewriteRule ^{0}$ {1} [R=301,L]\n".format(removed_leading_slash, line[1]))
# Close the file
output_path.close()
if __name__ == '__main__':
main()