如何在URL中添加请求头实现PDF自动下载(仿Amazon S3临时URL)
The key here is to mimic Amazon S3’s approach by adding a query parameter to your PDF URL that tells the server to send the Content-Disposition: attachment header—this forces browsers to download the file instead of displaying it. Here’s how to make this work:
Step 1: Modify Your PDF URL
Append the response-content-disposition=attachment query parameter to your existing URL. For your example, it would look like this:
http://doc.local.com/storage/temporary/2020-02-19/c3e175b4706492be8c0d90e497c86ea7/test.pdf?response-content-disposition=attachment
Step 2: Configure Your Server to Respect the Parameter
This URL only works if your web server is set up to check for this query parameter and adjust the response headers accordingly. Below are configurations for the two most common servers:
For Nginx
Add this to your server or location block that handles PDF files:
location ~* \.pdf$ { # Check if the query parameter exists and is set to "attachment" if ($arg_response_content_disposition = "attachment") { # Send the header to trigger download add_header Content-Disposition "attachment; filename=$basename"; } # Keep your existing configuration for serving PDFs (e.g., root path, expires headers) }
For Apache
Enable mod_rewrite and mod_headers, then add this to your .htaccess file or Apache config:
RewriteEngine On # Detect the query parameter and set an environment variable RewriteCond %{QUERY_STRING} (^|&)response-content-disposition=attachment(&|$) RewriteRule ^ - [E=TRIGGER_DOWNLOAD:1] # Set the Content-Disposition header when the environment variable is present Header set Content-Disposition "attachment" env=TRIGGER_DOWNLOAD
Why This Works
When the server receives the URL with the response-content-disposition=attachment parameter, it adds the Content-Disposition: attachment header to the response. Browsers interpret this header as a signal to download the file instead of rendering it in the window, just like S3’s temporary URLs do.
Alternative If Server Configuration Isn’t Possible
If you can’t modify your server’s settings, you could create a lightweight proxy endpoint (e.g., a simple PHP script) that fetches the PDF and sends the download headers—but since you mentioned wanting to avoid that specific code, this should be a last resort. The server-side configuration approach is cleaner and aligns with your goal of using a direct URL.
内容的提问来源于stack exchange,提问作者Albert

