How Do I Add a rel="canonical" HTTP Header to Embedded PDF Files? I'm working on project where I would like to directly embed PDFs onto web pages. We'll be using Google's PDF viewer as the embed tool and implementing via a macro.

Here is the macro as it stands now: 

{% macro pdfEmbed(pdfLink, width="580", height="480") %}

    &lt;iframe src="https://drive.google.com/viewerng/viewer?embedded=true&amp;url={{ pdfLink }}" width="{{width}}px" height="{{height}}px"&gt;&lt;/iframe&gt;

{% endmacro %}


For SEO purposes, I'd like to set a rel="canonical" on the PDF to point to the entry on which the PDF is embedded so Google knows to index the parent page and not the PDF. From what I've read, the general best practice for how to do this with embedded PDFs is via HTTP headers. See here for more detail: https://moz.com/blog/how-to-advanced-relcanonical-http-headers

I'm struggling with how to implement it in practice. I think the best method would be to use {% header %} tag within the macro but I'm not sure if there's a way to target that at just PDF files? If that doesn't work, .htaccess could be an option but then I lose the ability to dynamically set the canonical on the PDF based on the URL of the entry that houses the PDF.

What is the best way to do this in Craft? I’m running a Craft 3 site FYI. 

Thanks!
So the problem you're running into is all about context. Twig operates in the context of the http request for the parent page; so any headers you add via Twig will be added to the page http header, which is not what you want.

This could be done server-side, as the article you reference mentions. But it becomes a bit more involved when we're dealing with dynamic content, which presumably we are if a CMS is in the mix.

Because what you need is something that will intercept the http requests for documents you want to affect the header of, and then set it based on the dynamic page where it's coming from.

You could accomplish this via a plugin by writing a controller that sets the headers and then returns the actual file. Then in your Twig code, you'd link to the controller not the PDF file.

If you're using SEOmatic for Craft CMS 3, you can use the built in seomatic.helper.seoFileLink() function to do all of this for you.