Deploy a request proxy

Updated at:
Copy as MD

In complex network environments, network carriers may hijack the default ApsaraVideo VOD domain name (*.aliyuncs.com), causing access failures. Deploy a dedicated proxy service to improve request success rates and stability.

Before you begin

The following example uses Alibaba Cloud Function Compute (FC) 3.0. Before you begin, review Function Compute billing.

Procedure

Follow these steps:

Note

If your Function Compute (FC) console displays the 2.0 interface, click Go to Function Compute 3.0 in the upper-right corner to switch to the new console.

Step 1: Create a function

  1. Go to the Functions page in the Function Compute (FC) console and click Create Function.

  2. Select Task Function and click Create Task Function. Configure the following parameters:

    • For the runtime environment, select Built-in Runtimes > Python.

    • Keep the default settings for other parameters or configure them as needed. For function type, select Task Function. In the elastic configuration, set the instance type to elastic instance with 0.35 vCPU, 512 MB of memory, and a 512 MB disk. Set the minimum number of instances to 0 (recommended) and the single-instance concurrency to 1. For the code upload method, select Use sample code. Then, click Create.

  3. Review your configuration and click Create.

Step 2: Deploy the code

  1. On the Function Details page, click the Code tab.

  2. Click Open WebIDE to open the code editor.

  3. Copy the following code into the editor.

    Sample code

    import json
    import logging
    import http.client
    from urllib.parse import urlencode
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger()
    def get_target_domain(region_id):
        # If region_id is not specified, use the default value.
        if not region_id:
            return "vod.cn-shanghai.aliyuncs.com"
        return f"vod.{region_id}.aliyuncs.com"
    def handler(event, context):
        try:
            # If the event is in bytes, decode it first.
            if isinstance(event, bytes):
                event = json.loads(event.decode('utf-8'))
            # Get queryParameters.
            query_params = event['queryParameters']
            logger.info(f"queryParameters: {query_params}")
            # Get and remove the RegionId parameter.
            region_id = query_params.pop('RegionId', None)
            target_domain = get_target_domain(region_id)
            # Build the query string.
            query_string = urlencode(query_params)
            path = f"/?{query_string}"
            logger.info(f"Forwarding to: {target_domain}{path}")
            # Forward the request.
            conn = http.client.HTTPSConnection(target_domain)
            conn.request('GET', path)
            # Get the response.
            response = conn.getresponse()
            body = response.read()
            # Process the response header to ensure there is only one Access-Control-Allow-Origin header.
            headers = dict(response.getheaders())
            # Set a single CORS header.
            headers['Access-Control-Allow-Origin'] = '*'
            return {
                'statusCode': response.status,
                'headers': headers,
                'body': body.decode('utf-8')
            }
        except Exception as e:
            logger.error(f"Error: {str(e)}")
            return {
                'statusCode': 500,
                'body': str(e)
            }
        finally:
            if 'conn' in locals():
                conn.close()
  4. Return to the Function Details page and click Deploy Code.

Step 3: Create a trigger

  1. On the Function Details page, click the Triggers tab.

  2. Click Create Trigger and select HTTP Trigger. We recommend setting Authentication Method to No Authentication and keeping the default settings for other parameters or changing them as needed. Enter a trigger name, set the version or alias to LATEST, and select the GET, POST, PUT, and DELETE request methods.

  3. Review your configuration and click OK.

Step 4: Verify the deployment

  1. On the trigger management page in the Function Compute console, find the HTTP trigger that you created and copy its public access address. Access this address in your browser to test the connectivity. You can also set the customVodServer property in your player to this address to access the proxy service.

  2. A successful connection confirms that the request proxy has been deployed.

Related documents