How to set variable value based on a subrequest

2.5k Views Asked by At

I am trying to set the value of a variable based on the result if the user is correctly logged in. I will use this variable for conditional ssi. I am using the auth_request module to authorise the user. This authorisation happens for all pages. The problem I am facing is that for 401/403 errors, NGINX passes 401 to the client. What I want to do is to show some pages anyway (even if the authorization fails), but set the variable (to the status of subrequest) for conditional ssi.

Config File

  location / {
    set $auth_status 100; #Default Value
    error_page 401 403 $show_anyway;
    error_page 500 = /auth_fallback;
    auth_request /auth_public;
    auth_request_set $auth_status $upstream_status;
    auth_request_set $show_anyway $request_uri;
  }

  location = /auth_public
  {
    proxy_pass http://localhost:8081;
    proxy_pass_request_body off;
    #return 200; #Tried this, but sub request doesn't fire.  
  }
1

There are 1 best solutions below

2
On BEST ANSWER

error_page 401 403 =200 ... can help. I tested the following config

ssi on;

location / {
    set $auth_status 100;
    auth_request /auth.php;
    auth_request_set $auth_status $upstream_status;
    error_page 401 403 =200 @process;
}

location @process {
    try_files $uri =404;
}

location = /auth.php {
    fastcgi_pass 127.0.0.1:9001;
    fastcgi_index index.php;
    include fastcgi_params;
}

Note about try_files inside @process - $uri/ droped for prevent internal redirect by index directive (if index file found). If internal redirect pass to location /, last error code will be used.