Search code examples
.htaccesspdfcontent-disposition

htaccess Set the Content-Disposition header conditionally for PDF files


I have a script made with PHP and JavaScript that with an API generates a PDF.

The domain has a .htaccess in which indicates that the PDF will be "downloaded".

  <FilesMatch "\.pdf$">
      Header set Content-Disposition "Attachment"
      Header set X-Content-Type-Options "nosniff"
  </FilesMatch>

Can I somehow keep the domain configuration and exclude the PDF file that is generated so that it can be viewed with the browser's built-in PDF viewer, rather than the browser prompting to download/save the file?

If I generate a new .htaccess file in the directory where the PDF is written, that .htaccess will only affect it, right?


Solution

  • I have tried creating a new htaccess inside the directory where I set the pdfs to be inline. <FilesMatch "\.pdf$"> Header set Content-Disposition "inline" </FilesMatch> And I can now view file.pdf online without downloading it. But in the rest of the domain if I try to open in any directory the pdfs are downloaded as indicated by the root htaccess. Is it wrong?

    No, that's not wrong. It's perfectly acceptable to override the header in a subdirectory (more specific) .htaccess file in this way. (Aside: You could potentially unset the header instead, since inline is the default value when omitted.)

    The alternative is to set the header conditionally in the parent config, based on the URL-path.

    Set the header conditionally

    For example, when the URL-path does not match the regex ^/directory($|/) (requires Apache 2.4):

    # /.htaccess
    
    <If "%{REQUEST_URI} !~ m#^/directory($|/)#">
        <FilesMatch "\.pdf$">
            Header set Content-Disposition "Attachment"
            Header set X-Content-Type-Options "nosniff"
        </FilesMatch>
    </If>
    

    Where /directory is the URL-path prefix to exclude.

    (Although you'd probably want to set the X-Content-Type-Options header regardless of location.)

    Note, however, that this is now based on the URL-path, not the file-path (as with using a second .htaccess file), if they happen to be different.


    Alternative using mod_setenvif (Apache 2.2+):

    SetEnvIf Request_URI "^/directory($|/)" INLINE_FILE
    <FilesMatch "\.pdf$">
        Header set Content-Disposition "Attachment" env=!INLINE_FILE
        Header set X-Content-Type-Options "nosniff"
    </FilesMatch>
    

    The SetEnvIf directive sets the INLINE_FILE env var if a URL-path is requested that matches the stated regex (ie. the directory to exclude). The Content-Disposition header is then set conditionally if the INLINE_FILE env var is not set (as denoted by the ! prefix).