Nginx internal 指令限制访问图片资源文件

Nginx 的 internal 指令可以用来限制 Web 公共目录下的图片等资源文件被任意用户直接访问。一个明显的使用场景是,对于用户上传的认证图片,属于个人隐私资源,不应该让所有用户都能访问得到,通常只能由管理员审核时查看。

假定需要限制访问的图片的 URL 路径是 /images/auth-pictures/,Nginx 进行如下配置:

location ^~ /images/auth-pictures/ {
  internal;
}

重启 Nginx,直接访问 /images/auth-pictures/ 下的图片,会返回 404:

利用 PHP 在响应头加上 “X-Accel-Redirect” 域使请求重定向到真实的图片路径上面:

1 <?php
2 // 可以先进行身份判断有无访问权限
3 // ...
4 $name = $_GET['name'];
5 header('Content-Type: ' . getimagesize('./images/auth-pictures/' . $name)['mime']);
6 header('X-Accel-Redirect: /images/auth-pictures/' . $name);
7 die;

此时就可以通过 PHP 程序来重定向请求访问图片了:

 

原文地址:https://www.cnblogs.com/imzhi/p/nginx-restrict-access-with-internal-directive.html