nginx autoindex目录列表功能下载txt文件时文件直接在浏览器打开而非下载

该博客内容涉及Web服务器配置,主要讲解如何在location块中设置规则,当用户请求特定文件类型(如txt, doc, pdf等)时,服务器将自动以附件形式下载这些文件,并设置相应的内容类型。通过添加Content-Disposition和Content-Type头,确保文件以安全方式传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       location / {
		    if ($request_filename ~* ^.*?.(txt|doc|pdf|rar|gz|zip|docx|exe|xlsx|ppt|pptx)$)
            {
				add_header Content-Disposition 'attachment';
                add_header Content-Type: 'APPLICATION/OCTET-STREAM';
            }

			autoindex on;
            root   html;
            index  index.html index.htm;
        }

在location中添加如下内容

if ($request_filename ~* ^.*?.(txt|doc|pdf|rar|gz|zip|docx|exe|xlsx|ppt|pptx)$)
            {
                add_header Content-Disposition 'attachment';
                add_header Content-Type: 'APPLICATION/OCTET-STREAM';
}

Nginx中配置下载文件,可以通过以下步骤实现: 1. **配置Nginx服务器块**:首先,需要在Nginx的配置文件(通常是`nginx.conf`)中定义一个服务器块。 2. **设置文件路径**:在服务器块中,指定文件所在的目录。 3. **配置下载路径**:使用`location`指令配置下载路径,并设置相应的权限和头信息。 以下是一个示例配置,假设我们要下载文件存放在`/var/www/files`目录下: ```nginx server { listen 80; server_name your_domain.com; root /var/www/html; index index.html index.htm; location /download/ { alias /var/www/files/; autoindex on; autoindex_exact_size off; autoindex_localtime on; add_header Content-Disposition 'attachment'; add_header Content-Type 'application/octet-stream'; # 限制下载速度(可选) limit_rate 1m; } } ``` ### 配置说明: 1. **server_name**:替换为你的域名。 2. **root**:指定网站的根目录。 3. **location /download/**:定义下载路径为`/download/`,实际文件存放在`/var/www/files/`。 4. **autoindex**:启用目录列表,方便查看文件。 5. **add_header Content-Disposition 'attachment'**:设置头信息,强制浏览器下载文件而不是直接打开。 6. **add_header Content-Type 'application/octet-stream'**:设置文件类型为二进制流,适用于各种类型的文件。 7. **limit_rate**:限制下载速度,防止带宽占用过高。 通过上述配置,用户可以通过访问`http://your_domain.com/download/filename`来下载文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值