title: How to create rewrite rule to Rename PDF file on the fly while Downloading using nginx?
body: <p>i am working on site where i am allowing users to download PDF files.
  Each PDF file is stored on server using random hash names, 
  eg.</p>
  
  <pre><code>file
  768E1F881783BD61583D64422797632A35B6804C.pdf 
  is stored in
  /usr/share/nginx/html/contents/7/6/8/E/1/768E1F881783BD61583D64422797632A35B6804C.pdf 
  </code></pre>
  
  <p>now i can try to give users the direct location of file , but the file name after its being downloaded is shown as 768E1F881783BD61583D64422797632A35B6804C.pdf and i would like to rename the file on the fly, i can achive this using php like this</p>
  
  <pre><code>&lt;?php
  // We'll be outputting a PDF  
  header('Content-type: application/pdf');
  
  // It will be called downloaded.pdf  
  header('Content-Disposition: attachment; filename="downloaded.pdf"');
  
  // The PDF source is in original.pdf  
  readfile('original.pdf');
  ?&gt; 
  </code></pre>
  
  <p>ref: <a href="https://stackoverflow.com/questions/1826804/rename-pdf-file-to-be-downloaded-on-fly">Rename pdf file to be downloaded on fly</a></p>
  
  <p>but i am lloking for something nginx rules directly which can rewrite download urls to path and rename too on the fly.</p>
  
  <p>How can i do so ?</p>
  
  <p>i have tried something like this.</p>
  
  <pre><code>location ^/download-pdf {
      alias   /usr/share/nginx/html/contents;
  if ($request_filename ~ ^.*?/[^/]*?_(.*?\..*?)$)
  {
      set $filename $1;
  }
  
  add_header Content-Disposition 'attachment; filename=$filename';
  }
  </code></pre>
  
  <p>so if i send user to this location</p>
  
  <pre><code>domain.com/download-pdf/768E1F881783BD61583D64422797632A35B6804C.pdf?title=this.is.test
  </code></pre>
  
  <p>then i want this file to be downloaded at users PC using title/filename as <strong>this.is.test.pdf</strong></p>
  
  <pre><code>/usr/share/nginx/html/contents/7/6/8/E/1/768E1F881783BD61583D64422797632A35B6804C.pdf 
  </code></pre>
  
  <p>can this be done only using <code>nginx</code> rewrite rules ? or i need to use <code>PHP</code> too ?</p>
  
  <hr>
  
  <p>update1:</p>
  
  <p>i have tried using it like this </p>
  
  <pre><code>location ^/download-pdf/([0-9A-F])/([0-9A-F])/([0-9A-F])/([0-9A-F])/([0-9A-F])/([0-9A-F]+).pdf$ {
      alias   /usr/share/nginx/basesite/html/contents;
  add_header Content-Disposition 'attachment; filename="$arg_title.pdf"'; 
  }
  </code></pre>
  
  <p>but the accessing url gives 404 not found error.</p>
  
  <hr>
  
  <p>update2:</p>
  
  <p>tried with this</p>
  
  <pre><code>location ~ /download-pdf {
  alias   /usr/share/nginx/html;
  rewrite ^/download-pdf/([0-9a-fA-F])/([0-9a-fA-F])/([0-9a-fA-F])/([0-9a-fA-F])/([0-9a-fA-F])/([0-9a-fA-F]+).pdf$ /contents/$1/$2/$3/$4/$5/$6.pdf break;
  add_header Content-Disposition 'attachment; filename="$arg_title.pdf"'; 
  }
  </code></pre>
  
  <p>still getting 404 not found.</p>