Apply rel="canonical" to PDFs | Community
Skip to main content
Level 2
September 29, 2023
Solved

Apply rel="canonical" to PDFs

  • September 29, 2023
  • 2 replies
  • 1420 views

Hi Team
I tried below one to Apply rel="canonical" to PDFs (We are using AEM as a cloud service), however It is not working as expected. Could someone please help me to fix this issue

 

<FilesMatch "\.pdf$"> RewriteRule ([^/]+)\.pdf $ - [E=FILENAME:%{HTTP_HOST}%{REQUEST_URI}] Header set Link '<https://%{FILENAME}e>; rel="canonical"' </FilesMatch>


Thanks in advance 🙂 

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by A_H_M_Imrul

@mahesh_tesla 

if your business allows, I would suggest to go for an easier solution with javascript

 

<script> document.addEventListener("DOMContentLoaded", function () { var pdfLinks = document.querySelectorAll('a[href$=".pdf"]'); pdfLinks.forEach(function (link) { link.setAttribute("rel", "canonical"); }); }); </script>

 

This JavaScript code will add the rel="canonical" attribute to all <a> elements with href attributes ending in ".pdf" when the page is loaded.

2 replies

A_H_M_Imrul
Community Advisor
A_H_M_ImrulCommunity AdvisorAccepted solution
Community Advisor
September 29, 2023

@mahesh_tesla 

if your business allows, I would suggest to go for an easier solution with javascript

 

<script> document.addEventListener("DOMContentLoaded", function () { var pdfLinks = document.querySelectorAll('a[href$=".pdf"]'); pdfLinks.forEach(function (link) { link.setAttribute("rel", "canonical"); }); }); </script>

 

This JavaScript code will add the rel="canonical" attribute to all <a> elements with href attributes ending in ".pdf" when the page is loaded.

Level 2
September 29, 2023

Thanks @a_h_m_imrul  for your solution. 
I will discuss your solution with my TL on Tuesday. Could you please suggest which approach is better: this one or making changes at the Dispatcher level?  

A_H_M_Imrul
Community Advisor
Community Advisor
September 30, 2023

In terms of the output, you can anticipate a comparable outcome from both solutions. Nevertheless, I am not entirely convinced that achieving this through the dispatcher rewrite is straightforward. Conversely, the JavaScript solution not only offers greater ease but also provides configurability.

kautuk_sahni
Community Manager
Community Manager
October 4, 2023

@mahesh_tesla Did you find the suggestion from @a_h_m_imrul helpful? Please let us know if more information is required. Otherwise, please mark the answer as correct for posterity. If you have found out solution yourself, please share it with the community.

Kautuk Sahni