Jeremy Felt

Open source student.

Configure Nginx to allow for embedded WordPress posts

The ability to embed WordPress posts in WordPress posts is a pretty sweet feature from 4.4 and I’ve been looking forward to finding ways of using it throughout WSU. Today, when I tried it for the first time, I got an error because of our strict X-Frame-Options header that we had set to SAMEORIGIN for all page views.

To get around this, I added a block to our Nginx configuration that modifies this header whenever /embed/ is part of the requested URL. It’s a little sloppy, but it works.

Before our final location block, I added a new one to capture /embed/:

# We'll want to set a different X-Frame-Option header on posts which
# are embedded in other sites.
location ~ /embed/ {
    set $embed_request 1;
    try_files $uri $uri/ /index.php$is_args$args;
}

This sets the $embed_request variable to be used later in our final .php location block:

location ~ \.php$ {
    try_files $uri =404;

    # Set slightly different headers for oEmbed requests
    if ( $embed_request = 1 ) {
        add_header X-Frame-Option ALLOWALL;
        add_header X-Content-Type-Options nosniff;
        add_header X-XSS-Protection "1; mode=block";
    }

    # Include the fastcgi_params defaults provided by nginx
    include /etc/nginx/fastcgi_params;
    ...etc...

Now, all URLs except those specifically for embedding are prevented from being used in iframes on other domains.

And here we are!

Still searching for Amelia

 

Responses and reactions

Replies

Gary replied on 

Embed pages set the "X-WP-embed: true" header, so a less hacky method would be to check for that before changing the X-Frame-Option setting.

    Jeremy Felt replied on 

    This sounds like magic I don't know how to perform yet. I tried checking `sent_http_x_wp_embed`, `upstream_http_x_wp_embed` and `http_x_wp_embed`, but they don't seem to be populated. Tips?

      Gary replied on 

      My nginx fu is weak, but here's a copy/pasta from the W.org config that may help:

      map $upstream_http_x_wp_embed $allow_embed_iframes {

      default 'SAMEORIGIN';

      true '';

      }

Leave a Reply

Your email address will not be published.

The only requirement for your mention to be recognized is a link to this post in your post's content. You can update or delete your post and then re-submit the URL in the form to update or remove your response from this page.

Learn more about Webmentions.