a6r a6r - 3 months ago 20
Apache Configuration Question

Access $_GET argument from inside .htaccess

I have on my server images with random names (f.e. "8a4f5d61.jpg") and I need to change name of those files using given GET argument.

So if I have such URL:


http://my.server/8a4f5d61.jpg?attachement=custom_name.jpg


and I want Apache to add header like this:


Header Content-Disposition: "attachement, filename=$_GET['attachement']"


so user will download this file already renamed into "custom_name.jpg".

I have no clue how to get that GET argument from inside .htaccess




On nginx it's very easy, here's my working nginx config:

location ~ ^/.*\.jpg$ {
if ($arg_inline) {
add_header Content-Disposition "inline; filename=$arg_inline";
}
if ($arg_attachement) {
add_header Content-Disposition "attachement; filename=$arg_attachement";
}
}


Is it achievable on Apache with .htaccess?

Answer

I haven't tested it, but theoretically, set an environment variable if your query matches the given criteria and later, use mod_headers' Header directive to set the header:

RewriteEngine On

RewriteCond %{QUERY_STRING} ^attachment=(.+)$ [NC]
RewriteRule ^ - [E=file_name:%1,L]

Header always set Content-Disposition "attachement; filename=%{file_name}e" env=file_name

where the %{file_name}e is the environment value for file_name.