在AWS中为每个用户设置动态子域名可以通过使用Amazon Route 53和Lambda函数来实现。以下是一个解决方法的代码示例:
import boto3
def lambda_handler(event, context):
domain = event['domain']
user_id = event['user_id']
subdomain = f'{user_id}.{domain}'
route53 = boto3.client('route53')
response = route53.change_resource_record_sets(
HostedZoneId='',
ChangeBatch={
'Changes': [
{
'Action': 'UPSERT',
'ResourceRecordSet': {
'Name': subdomain,
'Type': 'CNAME',
'TTL': 300,
'ResourceRecords': [
{
'Value': ''
},
],
}
},
]
}
)
return {
'statusCode': 200,
'body': 'Subdomain created/updated successfully'
}
在Amazon API Gateway中创建一个新的API,将POST请求映射到上述Lambda函数。
在您的应用程序中,当用户需要创建或更新子域名时,向API发送POST请求:
import requests
api_url = ''
payload = {
'domain': '',
'user_id': ''
}
response = requests.post(api_url, json=payload)
if response.status_code == 200:
print('Subdomain created/updated successfully')
else:
print('Failed to create/update subdomain')
请注意替换代码中的以下占位符:
:您的Amazon Route 53托管区域的ID。
:您要将子域名指向的目标域名。
:API Gateway中创建的API的URL。
:您的主域名。
:用户的唯一标识符,用于创建与其相关联的子域名。当您的应用程序调用API发送POST请求时,Lambda函数将在Amazon Route 53中创建或更新相应的子域名记录。