Search code examples
url-rewritinghttp-headersurl-rewrite-modulecanonical-linkoutbound

Canonical URL and PDF with IIS rewrite module


I am trying to add a canonical url to PDF only using the IIS Rewrite module. I can't get it to work for some reason. Below is what I currently have.

Link: <http://www.example.com/downloads/whitepaper.pdf>; rel="canonical"

XML

<outboundRules rewriteBeforeCache="true">
<rule name="Canonical For PDF" preCondition="IsPDF">
                    <match serverVariable="RESPONSE_Link" pattern=".*" negate="false" />
                    <conditions>
                    </conditions>
                    <action type="Rewrite" value="&lt;{HTTP_HOST}{REQUEST_URI}>; rel=&quot;canonical&quot;" />
                </rule>
                <preConditions>
                    <preCondition name="IsPDF">
                        <add input="{REQUEST_FILENAME}" pattern="\.pdf.*" />
                    </preCondition>
                </preConditions>
      </outboundRules>

Solution

  • I couldn't get this to work so I did this instead through the Global.asax , Application_BeginRequest

      if (Request.FilePath.EndsWith(".pdf"))
      {
          Response.AddHeader("Link", $"<{Request.Url.AbsoluteUri.Split('?')[0]}>; rel=\"canonical\"");
      }