Created
October 9, 2025 08:20
-
-
Save ensean/f75a782a54f7ff52516e2efeb471dfbf to your computer and use it in GitHub Desktop.
Lambda@Edge for modify m3u8 structure
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
| import urllib3 | |
| import re | |
| def lambda_handler(event, context): | |
| request = event['Records'][0]['cf']['request'] | |
| response = event['Records'][0]['cf']['response'] | |
| # Extract token from query string | |
| token = None | |
| for param in request['querystring'].split('&'): | |
| if param.startswith('token='): | |
| token = param.split('=')[1] | |
| break | |
| if not token or response['headers'].get('content-type', [{}])[0].get('value') != 'application/vnd.apple.mpegurl': | |
| return response | |
| try: | |
| # Fetch original content | |
| http = urllib3.PoolManager() | |
| origin_host = event['Records'][0]['cf']['config']['distributionDomainName'] | |
| url = f"https://{origin_host}{request['uri']}" | |
| print("url: " + url) | |
| resp = http.request('GET', url) | |
| original_content = resp.data.decode('utf-8') | |
| print("original_content: \n" + original_content) | |
| # Modify M3U8 content - only add token to EXT-X-KEY URIs | |
| def add_token_to_key(match): | |
| uri_part = match.group(1) | |
| separator = '&' if '?' in uri_part else '?' | |
| return f'URI="{uri_part}{separator}token={token}"' | |
| modified_content = re.sub(r'URI="([^"]+)"', add_token_to_key, original_content) | |
| print("modified_content: \n" + modified_content) | |
| response['body'] = modified_content | |
| return response | |
| except Exception as e: | |
| print(f"Error: {e}") | |
| return response | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Change HLS encryption m3u8 file to append querystring for encryption key request athentication, eg change m3u8 from
to