Return 从 FasctCGI 到 nginx 的响应

Return response from FasctCGI to nginx

我是 FastCGI 菜鸟,我遇到了一个问题和一些我找不到任何答案的问题,我想做的是使用 FastCGI 处理 url 凭据并批准或拒绝例如这是 url。 http://mydomain/myalias/image.jpg?key=ttttttttt

我想做的是将 key 参数发送给 fastCGI 进行一些处理,然后 return 发送给 nginx 200(确定)以提供文件或 403(禁止)。 这是我的 nginx 配置:

location /my_location/ {
    root   /var/www/html;
    index  index.html index.htm;
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_param  SCRIPT_FILENAME  /etc/nginx/conf.d/process_request.php;
    fastcgi_param  QUERY_STRING $uri;
    fastcgi_param  KEY_VALUE $arg_key;
    include /etc/nginx/fastcgi_params;
}

在我的 process_request.php 文件中,我可以使用以下命令成功读取 KEY_VALUE:

$_SERVER['KEY_VALUE'];

我想要的是 return 响应 nginx 我正在尝试的是:

header("Status: 200 OK");

header("Status: 403 forbidden");

但问题是它 return 一个响应代码为 200 或 403 的空白页面,只没有在浏览器中显示我的图像。 那么我缺少什么,我想在代码为 200 时显示图像?

在响应 200 的情况下,您必须 return 状态中的图像而不是 return。

你可以这样 return 图片 : Return a PHP page as an image.

Nginx 有一个功能可以完全满足您的需求,并且不会 PHP 与服务静态文件捆绑在一起。

auth_request

The ngx_http_auth_request_module module (1.5.4+) implements client authorization based on the result of a subrequest. If the subrequest returns a 2xx response code, the access is allowed. If it returns 401 or 403, the access is denied with the corresponding error code. Any other response code returned by the subrequest is considered an error.

您的配置类似于:

location /my_location/ {
  auth_request /access/auth;
  root   /var/www/html;
  index  index.html index.htm;
}

location /access/auth {
  fastcgi_pass   127.0.0.1:9000;
  fastcgi_param  SCRIPT_FILENAME  /etc/nginx/conf.d/process_request.php;
  fastcgi_param  QUERY_STRING $uri;
  fastcgi_param  KEY_VALUE $arg_key;
  include /etc/nginx/fastcgi_params;
}

在这种情况下,您的 PHP 脚本只会 return 200 进行身份验证,否则任何其他代码 (403) 都会 return 被禁止。您还可以使用 error_page 403 = /forbidden.html

之类的内容自定义 403 响应外观

如果 PHP returns 200,则 Nginx 将允许原始请求继续并直接从磁盘提供图像或其他内容以及图像的正确 headers .