Search code examples
apicloudflare

Forwading URL Through Cloudflare API


I'm trying to create a page rule using Cloudflare's API to forward http to https. Unfortunately, I don't think the documentation is 100% clear on how to do this. Here is the JSON object I'm currently passing to the POST body:

{
  "targets": [
    {
      "target": "url",
      "constraint": {
        "operator": "matches",
        "value": "http://exampletest.com/*"
      }
    }
],
  "actions": [{
    "id": "forwarding_url",
    "value": "https://exampletest.com/$1"
  }]
}

and here is the message I'm getting back:

{
"success": false,
"errors": [
    {
        "code": 1004,
        "message": "Page Rule validation failed: See messages for details."
    }
],
"messages": [
    {
        "code": 1,
        "message": ".settings[0].url: This value should not be blank.",
        "type": null
    },
    {
        "code": 2,
        "message": ".settings[0].statusCode: This value should not be blank.",
        "type": null
    }
],
"result": null

}

So it seems like I need to have a settings object somewhere, but any way I try to add the settings, I'm getting the same message. Does anyone know what I'm doing wrong here? Here is Cloudflare's Documentation on the subject. Not sure if I might be missing something:

https://api.cloudflare.com/#page-rules-for-a-zone-create-page-rule


Solution

  • Actually, just figured this one out. It looks like this is the correct format:

    {
      "targets": [
        {
          "target": "url",
          "constraint": {
            "operator": "matches",
            "value": "http://exampletest.com/*"
          }
        }
      ],
      "actions": [
        {
          "id": "forwarding_url",
          "value": {
            "url": "https://www.exampletest.com/$1",
            "status_code": 301
          }
        }
      ]
    }