Search code examples
.htaccesspdf

.htacces rule for specific filename pdf


I'm trying to assign a canonical to specific Pdf (based on their filename) and at the same time I need to assign a generic canonical to all others pdf.

I'm actually using these rules:

<Files The-life-of-RINGO.pdf> 
Header add Link '<https://website.com/01/canonical/>; rel="canonical"'
</Files>
<Files Product-new.pdf> 
Header add Link '<https://website.com/02/canonical/>; rel="canonical"'
</Files>
<Files Presentation.pdf> 
Header add Link '<https://website.com/03/canonical/>; rel="canonical"'
</Files>
<Files The-rulebook.pdf> 
Header add Link '<https://website.com/04/canonical/>; rel="canonical"'
</Files>
<Files Adventure-trial.pdf> 
Header add Link '<https://website.com/05/canonical/>; rel="canonical"'
</Files>

# PDF Canonical
RewriteRule ([^/]+)\.pdf$ - [E=FILENAME:$1]
<FilesMatch "\.pdf$">
    Header add Link '<https://www.website.com/uploads/%{FILENAME}e>; rel="canonical"'
</FilesMatch>

Problem is that now htaccess adds to canonical to that specific pdf by applying to different rules.

For example to The-life-of-RINGO.pdf it adds:

Is there a way to add a conditional logic to ignore the generic pdf RewriteRule for to the first 5 files?

Thank you.


Solution

  • Do it the other way around - set the canonical for all PDFs first, and then use set instead of add for the individual ones.

    https://httpd.apache.org/docs/2.4/mod/mod_headers.html#header:

    add: The response header is added to the existing set of headers, even if this header already exists. This can result in two (or more) headers having the same name. This can lead to unforeseen consequences, and in general set, append or merge should be used instead.

    set: The response header is set, replacing any previous header with this name. The value may be a format string.