I'm attempting to setup Canonical links for a number of PDF and images files on my website.
Example Folder Structure:
/index.php
/docs/
file.pdf
/folder1/
file.pdf
/folder2/
file1.pdf
file2.pdf
/img/
sprite.png
/slideshow/
slide1.jpg
slide2.jpg
Example PDF URL to Canonical URL:
http://www.example.com/docs/folder1/file.pdf --> http://www.example.com/products/folder1/
I am trying to avoid having to put individual .htaccess files in each of the sub-folders that contain all of my images and PDFs. I currently have 7 "main" folders, and each of these folders have any where from 2-10 sub-folders, and most sub-folders have their own sub-folders. I have roughly 80 PDFs, and even more images.
I'm looking for a (semi)dynamic solution where all files in a certain folder will have the Canonical Link set to a single url. I want to keep as much as possible in a single .htaccess file.
I know that <Files>
and <FilesMatch>
do not understand paths, and that <Directory>
and <DirectoryMatch>
don't work in .htaccess files.
Is there a fairly simple way to accomplish this?
Here is the solution !!!
you can use .htacess file for controlling header which is more simple way to manage headers.
How you can do ?
<Files testPDF.pdf > Header add Link '<http://<your_site_name>.com/ >; rel="canonical"' </Files>
Once you've added that to your .htaccess file, you'll need to test your header to ensure that it's working accurately
I don't know of a way to solve this with apache rules alone as it would require some sort of regex matching and reusing the result of the match in a directive, which isn't possible.
However, it's pretty simple if you introduce a php script into the mix:
Note that this would send requests for all jpg, png and pdf files to the script regardless of the folder name. If you want to include only specific folders, you could add another RewriteCond to accomplish that.
Now the canonical-header.php script:
Please consider this code untested and check that it works as expected across browsers before releasing it to production.
For an IIS solution, try something like this.
this was added to a function which generated a PDF version of the webpage :)