Wednesday, April 2, 2014

Using multiple hosts for X-Frame-Options on Nginx

This week I was implementing the X-Frame-Options to prevent clickjacking on a website which requires multiple XFO entries for different providers. This is how I did it.

First, you need the Rewrite module in your Nginx - it should be ok unless you built your package without it. In my case, the entries were needed for:

  • myprovider1.mydomain.com (partner)
  • myprovider2.mydomain.com (partner)
  • myusualprovider.mydomain.com (usual assets provider)

Depending on the engine being used the location may change, for example for an HTML server it would be located on 'location /', however for a PHP website it might need to be located on the 'location ~ \.php$'


location / {
[...]
        set $external_origin 0;
        if ($http_origin ~ "mydomain.com$") {
                add_header X-Frame-Options  "ALLOW-FROM $http_origin";
                set $external_origin 1;
        }
        if ($external_origin = "0") {
                add_header X-Frame-Options "ALLOW-FROM http://myusualentry.mydomain.com";
        }
[...]
}

Since at the moment Nginx does not have a if ... else we need to work with variables. If we access www.mydomain.com directly will make the $http_origin variable empty and the $external_origin variable will remain as '0', assigning the usual asset provider as the XFO value (add_header X-Frame-Options "ALLOW-FROM http://myusualentry.mydomain.com";). If the website it's called trough another website, it will check whether the call was done from a *mydomain.com origin, if so it will add the origin host as an allowed XFO entry and change $external_origin to 1 so it won't add anymore entries - according to the rfc, only one value is accepted.

No comments:

Post a Comment