Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return response from FasctCGI to nginx

Tags:

php

nginx

fastcgi

I am a FastCGI noob and i am facing a problem and some questions that i can't find any answers for, what I am trying to do is using FastCGI to process url credentials and either approve or deny for example this is the url. http://mydomain/myalias/image.jpg?key=ttttttttt

What I want to do is send the key argument to the fastCGI to do some processing and return to nginx either 200(OK) to serve the file or 403 (forbidden). here is my nginx configuration:

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;
}

And in my process_request.php file i can successfully read the KEY_VALUE using this:

$_SERVER['KEY_VALUE'];

What I want is to return response to nginx what I was trying is:

header("Status: 200 OK");

or

header("Status: 403 forbidden");

But the problem is it return a blank page with response code 200 or 403 Only without showing my image the browser. So what I am missing, I want to display the image when code is 200 ?

like image 762
Yasmin Reda Avatar asked Dec 22 '25 13:12

Yasmin Reda


1 Answers

Nginx has a feature that does exactly what you want and does not tie PHP up with serving static files.

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.

Your config would look something like:

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;
}

In this scenario, your PHP script would just return 200 for authenticated, otherwise any other code (403) would return forbidden. You can also customise the 403 response appearance using something like error_page 403 = /forbidden.html

If PHP returns 200, then Nginx will allow the original request to continue and serve the image or other content directly from disk along with the correct headers for the image.

like image 85
Steve E. Avatar answered Dec 24 '25 03:12

Steve E.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!