【原】阿里云可编程CDN 边缘脚本(EdgeScript)接入尝试

需求:

demo 根据来源IP返回国家码、邮编,根据UA判断是否是移动端

方案:

已知,国内CDN厂商的默认配置是不支持这种定制需求的,需要提交工单联系专业的人士去配置,好在阿里云支持这种边缘脚本的方式,降低了配置的门槛,同时也有庞大的函数库,能够像积木式地组合出个性化的CDN定制配置。

1. 准备代码

c_country = client_country()
c_region = client_region()
# 获取 Country-Code
if c_country {
    # say(concat('client_country:', c_country))
    add_req_header('X-Country-Code', c_country)
}
if c_region {
    # say(concat('client_region:', c_region))
    add_req_header('X-Region-Code', c_region)
}
# 判断UA
if $http_user_agent {
    ua = match_re($http_user_agent, '(Android|iPhone|iPad|iPod|Symbian|IEMobile|BlackBerry|networkbench|Windows Phone|MQQBrowser)')
    if ua {
        add_req_header('X-Is-Mobile-Viewer', 'true')
    } else {
        add_req_header('X-Is-Mobile-Viewer', 'false')
    }
}

2. 开始配置

接入后,并保存,发布到模拟环境

注意:边缘脚本需要在模拟环境先进行测试再发布到生产环境,先测,测没问题之后再上生产环境,同时,生产环境也是不支持直接修改的,需要先把生产的规则,先复制到测试环境,修改完了,测试没问题之后,再推到生产环境,这么做的目的是防止生产环境改错,造成大量不可用。

3. 模拟环境验证

绑定 IP 进行测试下

curl -x 42.123.119.100:80 -o /dev/null -v 'http://www.5179.top'

在 nginx 日志处,把加的两个 header 也打印出来

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$http_x_country_code"     "$http_x_is_mobile_viewer"';

nginx 的访问日志如下:

# 本地机器访问
100.122.16.158 - - [30/May/2021:18:06:40 +0800] "GET / HTTP/1.1" 200 7770 "-" "curl/7.64.1" "111.199.187.234, 116.211.219.36" "CN" "false"
# 国外机器访问
100.122.16.250 - - [30/May/2021:18:15:05 +0800] "GET / HTTP/1.1" 200 7770 "-" "curl/7.29.0" "67.218.156.67, 116.211.219.36" "US" "false"

可以看到 Country-Code 已经都能正常取到。

4. 将规则推送至生产环境

此时,生产环境已经生效

5. 如何对上述规则进行debug

然后再次访问的时候,可以在 URL 的后面添加 ?_es_dbg=wow 的形式去获取 debug 的过程,

例如:curl http://www.5179.top?_es_dbg=wow -Iv

对应的1、2、5、9、13、17,其实是对应的代码行号,根据这个 trace 我们可以很方便的对自定义的规则进行调试。

参考:

1.概述:https://help.aliyun.com/document_detail/126565.html?spm=a2c4g.11186623.6.717.21e71e0cN9Cuw8

2.场景demo:https://help.aliyun.com/document_detail/126571.html?spm=a2c4g.11186623.6.738.4a90238f8ZzYVZ

3.视频:https://developer.aliyun.com/live/2690

原文地址:https://www.cnblogs.com/liyongjian5179/p/14828672.html