AdrianD
AdrianD

Reputation: 19

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

Upvotes: 1

Views: 1788

Answers (2)

AdrianD
AdrianD

Reputation: 19

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>

Upvotes: 1

Amit Verma
Amit Verma

Reputation: 41219

To dynamically add header link based on the requested filename, you can use this

 <FilesMatch "^(?<uripart[^0-9]+)[0-9]+\.pdf$">


Header add Link  '<https://www.website.com/pdf/%{env:MATCH_URIPART}.pdf >;rel="canonical"'
</FilesMatch>

uripart is part of the uri string we capture from the requested pdf file and we use it in the header target using ENV:MATCH variable.

Upvotes: 0

Related Questions