简体   繁体   中英

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

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM