Skip to main content

Create and use CDN rule templates

A template is a preset rule for CDN resources — it contains all necessary settings: file paths, an origin pull protocol, and enabled and disabled options. A template pre-fills those settings when a rule is created.

CDB provides built-in templates called System, while custom templates store a path and options for one account.

Custom template

Set the file path, origin pull protocol, and any option overrides that the template should store.

  1. 1

    Open the template form

    In the CDB Customer Portal, open the CDN resource settings. On the Rules tab, open the Templates section and click Create template.

    Templates page showing system templates list and Create template button
  2. 2

    Set the template fields

    Complete the form:

    1. Specify the template name. Templates can be searched by name after creation.
    2. Specify the path to the file or folder. The path must start with ^/ or / and can be a regular expression.
    3. Select the protocol the CDN uses to pull those files. If the files are available over the same protocol configured for the origin, select Inherit from resource. Otherwise select HTTP, HTTPS, or both protocols.
    4. (Optional) Set any option overrides the template should store.
    Create template form with Template name, Match criteria, Origin pull protocol, and Options fields
  3. 3

    Create the template

    Click Create template.

System templates

System templates are built-in presets covering common CDN use cases. They are labeled System in the Templates section.

Templates page with five system templates each labeled System

Video segments template (.ts) is a rule template for caching chunks (streaming via CDN).

Playlists template (.m3u8) is a rule template for caching playlists.

Let's Encrypt HTTP-01 challenge validates a certificate issued with the HTTP-01 challenge outside the Customer Portal. Create the CDN resource and a rule from this template before requesting the certificate, because the resource settings block validation until that rule exists.

Static content is a rule template for caching static files of the resources integrated with the DNS.

Image optimization applies Image Stack, a paid add-on, to matching image files. Turn it on from the resource options before adding the template, and narrow the file path when only some files should match.

Rule from a template

A template pre-fills the rule form, so only the final adjustments remain before saving.

  1. 1

    Select a template

    Open the CDN resource settings. On the Rules tab, click Create rule and select a template.

    Create rule dropdown showing Create blank rule option and system templates list
  2. 2

    Confirm the pre-filled settings

    The form opens with settings from the template. Review them and edit them when the saved path or options should differ.

    Create rule form pre-filled with settings from the selected template
  3. 3

    Create the rule

    Click Create rule.

Store a path and option overrides as a custom template, or create a CDN resource rule from the settings of a system template. Find the resource ID in list CDN resources.

An API token is required, along with the ID of the CDN resource that receives the rule.

export GCORE_API_KEY="{YOUR_API_KEY}"
export CDN_RESOURCE_ID="{YOUR_RESOURCE_ID}"

Custom template

Match files with rule, as a path or a regular expression. For ruleType 0, start that pattern with ^/ or /.

Set overrideOriginProtocol to HTTP or HTTPS to pull over that protocol, or to MATCH when the origin serves the files over both. Leave the field out to keep the protocol already set on the resource.

from gcore import CDB

client = CDB()

template = client.cdn.rule_templates.create(
    name="static-images",
    rule="/images/*.png",
    rule_type=0,
    override_origin_protocol="HTTPS",
    options={"edge_cache_settings": {"enabled": True, "value": "4d"}},
)
print(template.id, template.name, template.default, template.override_origin_protocol)
package main

import (
    "context"
    "fmt"

    gcore "github.com/G-Core/gcore-go"
    "github.com/G-Core/gcore-go/cdn"
    "github.com/G-Core/gcore-go/packages/param"
)

func main() {
    client := gcore.NewClient()
    ctx := context.Background()

    template, err := client.CDN.RuleTemplates.New(ctx, cdn.RuleTemplateNewParams{
        Name:                   param.NewOpt("static-images"),
        Rule:                   "/images/*.png",
        RuleType:               0,
        OverrideOriginProtocol: cdn.RuleTemplateNewParamsOverrideOriginProtocolHTTPS,
        Options: cdn.RuleTemplateNewParamsOptions{
            EdgeCacheSettings: cdn.RuleTemplateNewParamsOptionsEdgeCacheSettings{
                Enabled: true,
                Value:   param.NewOpt("4d"),
            },
        },
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(template.ID, template.Name, template.Default, template.OverrideOriginProtocol)
}
curl -X POST "https://api.cdb-staging.cdn.orange.com/cdn/resources/rule_templates" \
  -H "Authorization: APIKey $GCORE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "static-images",
    "rule": "/images/*.png",
    "ruleType": 0,
    "overrideOriginProtocol": "HTTPS",
    "options": {
      "edge_cache_settings": {"enabled": true, "value": "4d"}
    }
  }'

The API returns HTTP 201:

{
  "id": 1005,
  "name": "static-images",
  "default": false,
  "template": true,
  "rule": "/images/*.png",
  "ruleType": 0,
  "weight": 1,
  "overrideOriginProtocol": "HTTPS",
  "options": {
    "edge_cache_settings": {"enabled": true, "value": "4d"}
  }
}

System templates

A custom template belongs to one account, while a system template is shared. default is true on a system template, and changing or deleting it fails with HTTP 403.

{"message": "You do not have permission to perform this action."}
from gcore import CDB

client = CDB()

for template in client.cdn.rule_templates.list(limit=100):
    print(template.id, template.name, template.default, template.rule, template.weight)
package main

import (
    "context"
    "fmt"

    gcore "github.com/G-Core/gcore-go"
    "github.com/G-Core/gcore-go/cdn"
)

func main() {
    client := gcore.NewClient()
    ctx := context.Background()

    page, err := client.CDN.RuleTemplates.List(ctx, cdn.RuleTemplateListParams{})
    if err != nil {
        panic(err)
    }
    for _, template := range page.Results {
        fmt.Println(template.ID, template.Name, template.Default, template.Rule, template.Weight)
    }
}
curl -X GET "https://api.cdb-staging.cdn.orange.com/cdn/resources/rule_templates?limit=100" \
  -H "Authorization: APIKey $GCORE_API_KEY"

The API returns:

{
  "count": 5,
  "next": null,
  "previous": null,
  "results": [
    {
      "id": 35462,
      "name": "Playlists template (.m3u8)",
      "default": true,
      "rule": "/.*\\.m3u8$",
      "ruleType": 0,
      "weight": 0
    },
    {
      "id": 35463,
      "name": "Video segments template (.ts)",
      "default": true,
      "rule": "/.*\\.ts$",
      "ruleType": 0,
      "weight": 0
    },
    {
      "id": 92195,
      "name": "Let's Encrypt HTTP-01 challenge",
      "default": true,
      "rule": "/.well-known/acme-challenge/",
      "ruleType": 0,
      "weight": 1
    },
    {
      "id": 74028,
      "name": "Static content",
      "default": true,
      "rule": "/.*\\.(js|css|bmp|jpg|jpeg|gif|png|svg|ico|json|ttf|ttc|otf|eot|woff|woff2|webp|zip|tgz|gz|rar|bz2|doc|docx|rtf|xls|xlsx|exe|pdf|ppt|pptx|txt|tar|mid|midi|wav|swf|flv|mp3|mp4)",
      "ruleType": 0,
      "weight": 1
    },
    {
      "id": 89562,
      "name": "Image optimization",
      "default": true,
      "rule": "/.*\\.(jpg|jpeg|png)",
      "ruleType": 0,
      "weight": 1
    }
  ]
}

Rule from a template

Read the template, then use its rule, ruleType, and configured options to create the rule. If overrideOriginProtocol is empty, leave it out and the rule keeps the resource protocol.

Skip weight. Playlist and video templates store 0, but a rule needs 1 or higher, so leaving the field out gives the rule weight 1.

{"errors": {"weight": ["Ensure this value is greater than or equal to 1."]}}
from gcore import CDB

client = CDB()

template = next(
    item
    for item in client.cdn.rule_templates.list(limit=100)
    if item.name == "Playlists template (.m3u8)"
)
options = template.options
rule = client.cdn.cdn_resources.rules.create(
    12345,
    name=template.name,
    rule=template.rule,
    rule_type=template.rule_type,
    options={
        "browser_cache_settings": {
            "enabled": options.browser_cache_settings.enabled,
            "value": options.browser_cache_settings.value,
        },
        "edge_cache_settings": {
            "enabled": options.edge_cache_settings.enabled,
            "value": options.edge_cache_settings.value,
        },
    },
)
print(rule.id, rule.rule, rule.weight, rule.active)
package main

import (
    "context"
    "fmt"

    gcore "github.com/G-Core/gcore-go"
    "github.com/G-Core/gcore-go/cdn"
    "github.com/G-Core/gcore-go/packages/param"
)

func main() {
    client := gcore.NewClient()
    ctx := context.Background()

    page, err := client.CDN.RuleTemplates.List(ctx, cdn.RuleTemplateListParams{})
    if err != nil {
        panic(err)
    }
    var selected *cdn.RuleTemplate
    for i := range page.Results {
        if page.Results[i].Name == "Playlists template (.m3u8)" {
            selected = &page.Results[i]
            break
        }
    }
    if selected == nil {
        panic("playlist template not found")
    }
    browser := selected.Options.BrowserCacheSettings
    edge := selected.Options.EdgeCacheSettings
    rule, err := client.CDN.CDNResources.Rules.New(ctx, 12345, cdn.CDNResourceRuleNewParams{
        Name:     selected.Name,
        Rule:     selected.Rule,
        RuleType: selected.RuleType,
        Options: cdn.CDNResourceRuleNewParamsOptions{
            BrowserCacheSettings: cdn.CDNResourceRuleNewParamsOptionsBrowserCacheSettings{
                Enabled: browser.Enabled,
                Value:   browser.Value,
            },
            EdgeCacheSettings: cdn.CDNResourceRuleNewParamsOptionsEdgeCacheSettings{
                Enabled: edge.Enabled,
                Value:   param.NewOpt(edge.Value),
            },
        },
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(rule.ID, rule.Rule, rule.Weight, rule.Active)
}
curl -X GET "https://api.cdb-staging.cdn.orange.com/cdn/resources/rule_templates/35462" \
  -H "Authorization: APIKey $GCORE_API_KEY"

Use the playlist path and cache options from that response to create the rule.

curl -X POST "https://api.cdb-staging.cdn.orange.com/cdn/resources/$CDN_RESOURCE_ID/rules" \
  -H "Authorization: APIKey $GCORE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Playlists template (.m3u8)",
    "rule": "/.*\\.m3u8$",
    "ruleType": 0,
    "options": {
      "browser_cache_settings": {"enabled": true, "value": "0"},
      "edge_cache_settings": {"enabled": true, "value": "2s"}
    }
  }'

The API returns HTTP 201:

{
  "id": 10001,
  "name": "Playlists template (.m3u8)",
  "rule": "/.*\\.m3u8$",
  "ruleType": 0,
  "weight": 1,
  "active": true,
  "overrideOriginProtocol": null,
  "options": {
    "browser_cache_settings": {"enabled": true, "value": "0"},
    "edge_cache_settings": {"enabled": true, "value": "2s"}
  }
}

A custom rule template stores a path and cache options. A CDN rule created from the playlist system template applies that template to .m3u8 files with the Terraform provider v2.

Create a custom template

Store the path, the origin pull protocol, and the CDN cache lifetime on the template. Set weight to 1. Leaving weight unset makes the next plan clear the value the API stored.

resource "gcore_cdn_rule_template" "static_images" {
  name                     = "static-images"
  rule                     = "/images/*.png"
  rule_type                = 0
  override_origin_protocol = "HTTPS"
  weight                   = 1

  options = {
    edge_cache_settings = {
      enabled = true
      value   = "4d"
    }
  }
}

After terraform apply, the account has a custom template named static-images. default is false. The template stores the path /images/*.png, origin pull over HTTPS, and a CDN cache lifetime of 4d.

Create a rule from a system template

Read the templates and select Playlists template (.m3u8). Copy its path and cache options onto the rule. The template stores weight 0. Set the rule weight to 1 and active to true. Leaving weight or active unset makes the next plan change the rule. Plan can warn that deprecated option fields on other templates in the list were read. The playlist rule is still created.

data "gcore_cdn_rule_templates" "account" {}

locals {
  playlists = one([
    for template in data.gcore_cdn_rule_templates.account.items :
    template if template.name == "Playlists template (.m3u8)"
  ])
}

resource "gcore_cdn_origin_group" "example" {
  name = "my-origin-group"

  sources = [
    {
      source  = "example.com"
      enabled = true
    }
  ]
}

resource "gcore_cdn_resource" "example" {
  cname           = "cdn.example.com"
  origin_group    = gcore_cdn_origin_group.example.id
  origin_protocol = "HTTPS"
}

resource "gcore_cdn_resource_rule" "playlists" {
  resource_id = gcore_cdn_resource.example.id
  name        = local.playlists.name
  rule        = local.playlists.rule
  rule_type   = local.playlists.rule_type
  weight      = 1
  active      = true

  options = {
    browser_cache_settings = {
      enabled = local.playlists.options.browser_cache_settings.enabled
      value   = local.playlists.options.browser_cache_settings.value
    }
    edge_cache_settings = {
      enabled = local.playlists.options.edge_cache_settings.enabled
      value   = local.playlists.options.edge_cache_settings.value
    }
  }
}

After terraform apply, requests for .m3u8 files match /.*\.m3u8$. Browser caching uses the value 0, and CDN caching uses 2s.

Delete the template and the rule

Run terraform destroy to delete the resources that configuration declares. With only the custom template block, destroy deletes that template. With the playlist rule block, destroy also deletes the CDN resource and the origin group.

terraform destroy