Making a password-protected folder on Contao
Posted by Howard Richardson (comments: 0)
I recently tried adding HTTP authentication to a folder of downloadable PDFs on a Contao installation. This is the sort of authentication where the browser itself prompts you for a username and password and then Apache checks that, usually against a password file specified by .htaccess. It's a quick and dirty way of adding password protection to a directory of files, when all you need is the functionality and none of the fuss.
However, adding in the files using Contao's "downloads" content element, highlighted a shortcoming of this approach. The downloads content element prints you a nice link to the file, but when you click it, it funnels the whole file to you via PHP, totally bypassing the authentication.
After pulling my hair out over this one, and considering rewriting a special version of the download module which didn't act this way, I realised there was a much simpler solution. The files themselves were still directly linkable, and when you did so the authentication kicked in, so all I needed to do were come up with some Apache mod_rewrite rules to turn all file requests in that directory back into direct links. And so were born these two lines:
RewriteCond %{QUERY_STRING} ^file=files/pw_protected/(.*)
RewriteRule .* /files/pw_protected/%1? [L]
In this case files/pw_protected is the path of the password-protected folder. The rule matches any filename being passed as a parameter to Contao and then rewrites it directly as a straight link. The trailing question mark on the RewriteRule is to remove the QUERY_STRING from the rewritten URL. Being final, this rewrite rule needs to go before all other usual ones in the Contao root .htaccess file (but obviously inside the mod_rewrite section).
It works a treat, and no programming was required in the end. Hope this helps someone else deal with the same issue.
Add a comment