Expand my Community achievements bar.

Guidelines for the Responsible Use of Generative AI in the Experience Cloud Community.
SOLVED

Apply rel="canonical" to PDFs

Avatar

Level 2

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  

Topics

Topics help categorize Community content and increase your ability to discover relevant content.

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

@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.

View solution in original post

4 Replies

Avatar

Correct answer by
Community Advisor

@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.

Avatar

Level 2

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?  

Avatar

Community Advisor

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.

Avatar

Administrator

@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