Thanks in advance.
I have a json file stored in s3 bucket. I am referring that for any re-directs. Below is an example json file.
{
"redirects" :[
{
"url" : "/xxx/index.html",
"redirect_url": "/yyy/index.html",
"statusCode": 302
},
{
"url" : "/aaaa/index.html",
"redirect_url": "/bbb/index.html",
"statusCode": 301
},
{
"url" : "/ccc/ddd/index.html",
"redirect_url": "/eeee/index.html",
"statusCode": 301
}
]
}
However only the first entry of the redirects is taken by lambda and rest are ignored. Below is my python script for redirects. I have cloudfront in front.
import boto3
import json
s3 = boto3.resource('s3')
base_url= "testsite_com" ###Cannot post any site address on stackoverflow
def lambda_handler (event, context):
request = event['Records'][0]['cf']['request']
print(event)
content_object = s3.Object('cbtest.cb-infra.com', 'config/redirects.json')
file_content = content_object.get()['Body'].read().decode('utf-8')
json_content = json.loads(file_content)
for entries in json_content["redirects"]:
old_url = entries["url"]
redirect_uri = entries["redirect_url"]
status_code = entries["statusCode"]
new_url= base_url + redirect_uri
print(old_url)
if request["uri"] == old_url :
response = {
'status': status_code,
'statusDescription': 'Found',
'headers': {
'location': [{
'key': 'Location',
'value': new_url
}]
}
}
print(response)
print("uri matched: ", request["uri"], redirect_uri)
return response
else :
print("uri : ", request["uri"])
return request
Redirect for only 1st url i.e /xxx/index.html works. Rest are not getting redirected.
You're returning after the first iteration in the for
loop, either from the if
or else
statement, in Python a function exits after returning.