This topic provides examples of how to use EdgeScript to customize authentication, control request and response headers, implement custom rewrites and redirects, customize cache control, and configure throttling.
Custom authentication rules
Scenario
The request URI format is
/path/digest/?.ts?key=&t=.For requests for
.tsfiles, you need to implement custom hotlink protection with the following rules:Rule 1: If the request lacks the
torkeyparameter, the POP returns a 403 status code and adds theX-AUTH-MSGresponse header.Rule 2: The
tparameter specifies the expiration time. If the value of thetparameter is earlier than the current time, the POP returns a 403 status code and adds theX-AUTH-MSGresponse header. Note: Authentication may fail due to time discrepancies between the client and the /DCDN POP.Rule 3:
md5(private key + path + filename.extension) ==digest. If thedigestdoes not match, a 403 response is returned.
EdgeScript rule
# Check the request type. if eq(substr($uri, -3, -1), '.ts') { # Check if the required parameters exist. if or(not($arg_t), not($arg_key)) { add_rsp_header('X-AUTH-MSG', 'auth failed - missing necessary arg') exit(403) } # Check if the time parameter is a number. t = tonumber($arg_t) if not(t) { add_rsp_header('X-AUTH-MSG', 'auth failed - invalid time') exit(403) } # Check if the URL has expired. if gt(now(), t) { add_rsp_header('X-AUTH-MSG', 'auth failed - expired url') exit(403) } # Use regex to extract parts of the request URI for the authentication algorithm. pcs = capture_re($request_uri,'^/([^/]+)/([^/]+)/([^?]+)%?(.*)') sec1 = get(pcs, 1) sec2 = get(pcs, 2) sec3 = get(pcs, 3) if or(not(sec1), not(sec2), not(sec3)) { add_rsp_header('X-AUTH-MSG', 'auth failed - malformed url') exit(403) } key = 'b98d643a-9170-4937-8524-6c33514bbc23' # Concatenate the string for signature calculation. signstr = concat(key, sec1, sec3) digest = md5(signstr) # Compare the calculated signature with the digest from the request. if ne(digest, sec2) { add_rsp_header('X-AUTH-DEBUG', concat('signstr: ', signstr)) add_rsp_header('X-AUTH-MSG', 'auth failed - invalid digest') exit(403) } }
Custom request and response headers
The following example shows how to automatically rename a downloaded file.
Example:
add_rsp_header('Content-Disposition', concat('attachment;filename=', tochar(34), filename, tochar(34)))Adding the
Content-Disposition: attachmentresponse header to an HTTP response forces the client to download the response body. If thefilenameparameter is specified, the file is automatically saved with the name specified infilename. If the parameter is not specified, the default name is used.The value of
filenameis enclosed in double quotation marks. In the example,34is the ASCII code for a double quotation mark (""), which is converted to a character by thetocharfunction.
Output:
Content-Disposition: attachment;filename="monitor.apk"EdgeScript rule:
if $arg_filename {
hn = 'Content-Disposition'
hv = concat('attachment;filename=', $arg_filename)
add_rsp_header(hn, hv)
}Custom rewrites and redirects
Precise URI rewrite
Scenario
When a user request for
/hellois rewritten to/index.htmlwithin /DCDN, both the back-to-origin and cached URIs are changed to/index.html, and the parameters are preserved.EdgeScript rule
if match_re($uri, '^/hello$') { rewrite('/index.html', 'break') }
Rewrite a file extension
Scenario
The user request URI
/1.txtis rewritten to/1.<type URL parameter>on the DCDN node. This means that the value of thetypeparameter in the request URL replaces the file extension in the URI. For example,/1.txt?type=mp4is rewritten to/1.mp4?type=mp4. Then, a back-to-origin request is sent to retrieve the file, and the file is cached on the DCDN node.EdgeScript rule
if and(match_re($uri, '^/1.txt$'), $arg_type) { rewrite(concat('/1.', $arg_type), 'break') }
Convert a file extension to lowercase
Scenario
Convert the file extension in the URI to lowercase.
EdgeScript rule
pcs = capture_re($uri, '^(.+%.)([^.]+)') section = get(pcs, 1) postfix = get(pcs, 2) if and(section, postfix) { rewrite(concat(section, lower(postfix)), 'break') }
Add a URI prefix
Scenario
User requests for
^/nn_live/(.*)are rewritten on the DCDN node to/3rd/nn_live/$1.EdgeScript rule
pcs = capture_re($uri, '^/nn_live/(.*)') sec = get(pcs, 1) if sec { dst = concat('/3rd/nn_live/', sec) rewrite(dst, 'break') }
302 redirect
Scenario
Perform a 302 redirect from the root directory
/to the/app/movie/pages/index/index.htmlpage.EdgeScript rule
if eq($uri, '/') { rewrite('/app/movie/pages/index/index.html', 'redirect') }
302 redirect to an HTTPS URL
Scenario
Redirect a URI that matches the root directory (
^/$) tohttps://demo.aliyundoc.com/index.html. You can specify the destination URI as needed.http://demo.aliyundoc.comhttps://demo.aliyundoc.com
EdgeScript rule
if eq($uri, '/') { rewrite('https://demo.aliyundoc.com/index.html', 'redirect') }
Custom cache control
Scenario
Set a custom TTL for cached resources based on conditions such as the URI path or the response status code.
EdgeScript rule
if match_re($uri, '^/image') { set_cache_ttl('code', '301=10,302=5') } if eq(substr($uri, -4, -1), '.mp4') { set_cache_ttl('path', 5) } if match_re($uri, '^/201801/mp4/') { set_cache_ttl('path', 50) } if match_re($uri, '^/201802/flv/') { set_cache_ttl('path', 10) }NoteFor URIs starting with
/image, the cache TTL depends on the response status code: 10 seconds for a 301 and 5 seconds for a 302.
Custom throttling
Scenario
If the
spandunitparameters are specified, throttling is applied. Thespparameter specifies the speed limit value, and theunitparameter specifies the unit as KB or MB.EdgeScript rule
if and($arg_sp, $arg_unit) { sp = tonumber($arg_sp) if not(sp) { add_rsp_header('X-LIMIT-DEBUG', 'invalid sp') return false } if and(ne($arg_unit, 'k'), ne($arg_unit, 'm')) { add_rsp_header('X-LIMIT-DEBUG', 'invalid unit') return false } add_rsp_header('X-LIMIT-DEBUG', concat('set on: ', sp, $arg_unit)) limit_rate(sp, $arg_unit) return true }
Region- and ISP-based access control
- Use scenarios
- Access control is implemented by identifying the region and Internet service provider (ISP) of the IP address included in the client request.
- The following functions are used to identify the region and ISP of the client IP address. For more information, see Request logic.
client_region: Returns the region code of the client IP address.client_isp: Returns the ISP code of the client IP address.
EdgeScript rule
# Restrict by province. Block access if the province does not match. ip_region_id=client_region() if not(match_re(ip_region_id, '440000|370000')) { add_rsp_header('X-REGION-BLOCK-DEBUG', concat('hit ip_region_id:', ip_region_id)) exit(403) } # Restrict by ISP. Block access if the ISP does not match. ip_isp_id=client_isp() if not(match_re(ip_isp_id, '100017|100025')) { add_rsp_header('X-REGION-BLOCK-DEBUG', concat('hit ip_isp_id:', ip_isp_id)) exit(403) }
Video: EdgeScript configuration example
This video shows you how to configure an EdgeScript for a domain name in the CDN console, using a custom rate-limiting policy as an example. You will learn the entire workflow: adding the script, publishing it to the staging environment, testing it, deploying it to the production environment, and testing it in production.