Search code examples
regexapache.htaccessfilecanonical-link

.htaccess add Custom Header to File directive matching pattern


I have on my website many pdf's that ends with a digit although they are the same pdf.

I want to add a Canonical Link via .htaccess (using Files or FilesMatch) to the pdf's that ends with a digit to the corresponding pdf

I think the pattern needs to be {anything}-{digit}.pdf

Ex:

<Files my-pdf-name-ends-with-1.pdf>
    Header add Link '<https://www.website.com/pdf/my-pdf-name-ends-with.pdf>; rel="canonical"'
</Files>
<Files my-pdf-name-ends-with-2.pdf>
    Header add Link '<https://www.website.com/pdf/my-pdf-name-ends-with.pdf>; rel="canonical"'
</Files>

<Files newpdf45-that-ends-with-2.pdf>
    Header add Link '<https://www.website.com/pdf/newpdf45-that-ends-with.pdf>; rel="canonical"'
</Files>
<Files newpdf45-that-ends-with-77.pdf>
    Header add Link '<https://www.website.com/pdf/newpdf45-that-ends-with.pdf>; rel="canonical"'
</Files>

<Files other-pdf-name-that-ends-with-digit-45.pdf>
    Header add Link '<https://www.website.com/pdf/other-pdf-name-that-ends-with-digit.pdf>; rel="canonical"'
</Files>
<Files other-pdf-name-that-ends-with-digit-34.pdf>
    Header add Link '<https://www.website.com/pdf/other-pdf-name-that-ends-with-digit.pdf>; rel="canonical"'
</Files>

Thank you!


Solution

  • My solution

    <FilesMatch "^(?<uripart>[^0-9]+)(-)[0-9]+\.pdf$">
      <If "%{REQUEST_URI} =~ m#^/path/to/pdfs/#">
        RewriteRule .* - [E=FILENAME:https://%{HTTP_HOST}/path/to/pdfs/%{ENV:MATCH_URIPART}\.pdf]
        Header set Link '<%{FILENAME}e>; rel="canonical"'
      </If>
    </FilesMatch>
    <FilesMatch "^(?<uripart>[^0-9]+)\.pdf$">
      <If "%{REQUEST_URI} =~ m#^/path/to/pdfs/#">
        RewriteRule .* - [E=FILENAME:https://%{HTTP_HOST}%{REQUEST_URI}]
        Header set Link '<%{FILENAME}e>; rel="canonical"'
      </If>
    </FilesMatch>