This script takes as an input a CSV file, which contains two columns. There is an address which should be redirected in the first column and there is an addres which the first address should be redirected to. The script parses the file and creates a new file in the format, which matches the current format of our .htaccess file. After the file is generated, you just take it and append the it to the existing .htaccess file. This script was made specifically for briol. If you want to use somewhere else, just replace https://briol.cz with the real address. The script:
# Define the path to the input file (replace this with your actual file path)
input_file_path = './orphaned_urls.csv'
# Define the path to the output file
output_file_path = './redirects_output.txt'
# Function to process redirects and write to an output file
def process_redirects(input_path, output_path):
with open(input_path, 'r') as file:
lines = file.readlines()[1:] # Skip the header
htaccess_redirects = []
for redirect in lines:
try:
source_url, target_url = redirect.strip().split(',')
# Extracting the path and adding the caret (^) at the start of the source path
source_path = "^" + source_url.replace('https://www.briol.cz', '')
target_path = target_url.replace('https://www.briol.cz', '')
# Formatting the redirect rule
rule = f"redirectmatch 301 {source_path} {target_path}\n"
htaccess_redirects.append(rule)
except Exception as e:
print(f"Error processing line: {redirect}. Error: {e}")
# Write the formatted redirect rules to the output file
with open(output_path, 'w') as htaccess_file:
htaccess_file.writelines(htaccess_redirects)
# Call the function with your file paths
process_redirects(input_file_path, output_file_path)