Search code examples
.htaccessfilenamescontent-disposition

Add path name to downloading file name


I want people to be able to download several files that sum up lessons I am teaching. Files are pdf organized in folders like this:

.htaccess
01-science/
   lesson-1/
      notes.pdf
      slides.pdf
   lesson-2/
      notes.pdf
      slides.pdf
…

The .htaccess file already forces files to be downloaded with these commands:

<Files *.pdf>
   ForceType application/octet-stream
   Header set Content-Disposition attachment
</Files>

I am giving the direct URL to reach the files, for instance https://lessons.domain.my/01-science/lesson-1/notes.pdf. But, to avoid confusion, at downloading, I'd like filenames to be prefixed with folder names to give this:

01-science-lesson-1-notes.pdf
01-science-lesson-1-slides.pdf

Maybe a regex in the could do this, but I can't get which one… Thanks for any help!


Solution

  • Thanks to this answer, I have found the proper .htaccess:

    RewriteRule ^(.*)\.pdf$ - [E=FILENAME:$0]
    <FilesMatch "\.(?i:pdf)$">
        ForceType application/octet-stream
        Header set Content-Disposition "attachment; filename=%{FILENAME}e"
    </FilesMatch>
    

    Thus the URL https://lessons.domain.my/01-science/lesson-1/notes.pdf downloads the file notes.pdf under the name 01-science_lesson-1_notes.pdf which fits perfectly.

    As I do not know the .htaccess syntax very well, this remains opened to any better suggestion or comment…