Created
January 30, 2017 16:37
-
-
Save chadsaun/ccb4efebfc966d684d4e96849f243751 to your computer and use it in GitHub Desktop.
Python Script to Generate Nginx Configuration File From a CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
yourrewrites_csv = '{}/Desktop/yourrewrites.csv'.format(os.path.expanduser('~')) | |
csv_file = open(yourrewrites_csv, 'rU') | |
urls = csv.reader(csv_file) | |
iterurls = iter(urls) | |
# Skip the column headers | |
next(iterurls) | |
# Create additional columns to assist with sorting | |
list_to_sort = [] | |
for line in iterurls: | |
url = urlparse(line[0]) | |
query_key = 9 | |
if url.query: | |
query_key = 1 | |
list_to_sort.append([url.path, query_key] + line) | |
# Now sort the list by URL path | |
sortedlist = sorted(list_to_sort, key=lambda x: x[0]) | |
conf = '' | |
for key, group in groupby(sortedlist, lambda x: x[0]): | |
# Now sort this list by wether it has a query or not | |
sorted_group = sorted(group, key=lambda x: x[1]) | |
location_header = None | |
for line in sorted_group: | |
old_url = line[2] | |
new_url = line[3] | |
url = urlparse(old_url) | |
location_path = old_url | |
if url.query: | |
location_path = url.path | |
if not location_header: | |
location_header = 'location ={} {{\n'.format(location_path) | |
conf += location_header | |
if url.query: | |
conf += '\tif ($args ~ {}) {{\n\t\trewrite ^ {}? permanent;\n\t}}\n'.format(url.query, new_url) | |
else: | |
conf += '\trewrite ^ {} permanent;\n'.format(new_url) | |
conf += '}\n' | |
print(conf) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment