iRule to modify a content-security-policy header

Code is community submitted, community supported, and recognized as ‘Use At Your Own Risk’.

Short Description

This short iRule snippet can change specific directives in a content-security-policy header.

The script is only roughly tested, but maybe we can improve it together.


Full Code Snippet



when HTTP_RESPONSE_RELEASE priority 800 {
    # init
    set csp_fields ""
    set csp(directives) ""
    set csp(values) ""

    # configure
    lappend csp(directives) "frame-ancestors"
    lappend csp(values) "*"

    # iterate through directives from backend
    set org_csp_fields [split [HTTP::header Content-Security-Policy] ";"]
    foreach field $org_csp_fields {
        set directive [getfield [string trim $field] " " 1]
        set idx [lsearch -exact $csp(directives) $directive]
        if { $idx > -1 } {
            # append enforced value
            lappend csp_fields "$directive [lindex $csp(values) $idx]"
        else {
            # append original value
            lappend csp_fields $field

    # add missing directives
    set i 0
    foreach field $csp(directives) {
        set idx [lsearch -glob $csp_fields "${field}*"]
        if { $idx == -1 } {
            # missing, add it
            lappend csp_fields "${field} [lindex $csp(values) $i]"
        incr i

    # replace the header
    HTTP::header remove Content-Security-Policy
    HTTP::header insert Content-Security-Policy [join $csp_fields "; "]





Updated Jan 23, 2023
Version 2.0

Was this article helpful?


  • svs's avatar
    Icon for Cirrostratus rankCirrostratus

    Hi Juergen,

    thanks for sharing this iRule. Saved a lot of time and probably the day of my customer. 😉

    The only improvement could be to use HTTP::header replace, instead of HTTP::header remove and HTTP::header insert, because replace combines the power of remove and insert😊

    Hope to see you soon.

    Best regards,

  • Hi Sven,

    remove and insert is the better approach, because replace replaces only the first occurence of the header, if there are multiple ones.