.htaccess rewrite rule to append the date to the filename, using Content-Disposition header

Viewed 80

I am trying to download different file types like PDF, XLS, .jpg, .png, etc. directly from Joomla CMS via web browser. Documents and files like Word, Excel, Powerpoint, PDFs, .jpg, .png and text are stored in Joomla DOCman and when a user wants a file they click a link in DOCman menu in the website and the file is getting downloaded. I would like to get the date appended to the file name, when users download files like PDF, XLS, .jpg, .png, etc. from the website menu created. It loos like this is possible at server level using a htaccess rewrite rule, as the filename the browsers uses to save a file is included in the Content-Disposition header:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition

Is it possible to rewrite that header to append the date to the downloaded filename? I tried the below code in htaccess file for PDF file type, but it doesn't work as expected.

RewriteEngine On
RewriteRule [^/]+\.pdf$ - [E=FILENAME:$0]
<FilesMatch "\.(?i:pdf)$">
    Header set Content-Type application/octet-stream
    Header set Content-Disposition "attachment; filename=%{FILENAME-.date('Y-m-d').}e" 
</FilesMatch>

Any help to get the correct htaccess rewrite rule to accomplish the above, would be higly appreciated.

1 Answers

Yes it is possible. This was tested and works.

RewriteEngine On
RewriteRule ([^/]+)\.pdf$ - [E=FILENAME:$1]
<FilesMatch "\.(?i:pdf)$">
    Header set Content-Type application/octet-stream
    Header onsuccess set Content-Disposition "expr=attachment; filename=\"%{ENV:FILENAME}-%{TIME_YEAR}-%{TIME_MON}-%{TIME_DAY}\.pdf\"" env=FILENAME
</FilesMatch>

The Apache documentation for the Header directive shows that the %{VARNAME}e format specifier should be used for placing environment variables in the Header value. However, since the value is provided via an ap_expr expression in my code sample, the ap_expr function env (or maybe reqenv) should be used instead. The Header directive documentation says that within ap_expr expressions:

Function calls use the %{funcname:arg} syntax rather than funcname(arg).

Related