Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
Edit NGINX variable used in location with value of the request

I want to toggle the URL redirection of one location depending on a header value. The final goal is to toggle the URL rewriting depending on a cookie value.

For that, I set the following configuration.

server{
    ...
    set $toggle "off";
    location / {
        if ( $toggle = "on"){
            return 301 https://stackoverflow.com;
        }
    }
}

I need to change the value of the toggle variable before Nginx evaluate the code into the location. I set the following init function:

static ngx_int_t ngx_http_toggle_init(ngx_conf_t *cf){

ngx_http_handler_pt        *h;
ngx_http_core_main_conf_t  *cmcf;

cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);

h = ngx_array_push(&cmcf->phases[NGX_HTTP_SERVER_REWRITE_PHASE].handlers);
if (h == NULL) {
    return NGX_ERROR;
}

*h = ngx_http_toggle_handler;

return NGX_OK;
}

And the following handler:

static ngx_int_t ngx_http_toggle_handler(ngx_http_request_t *r){
ngx_int_t response;
response = ngx_http_toggle(r);
if(response != NGX_OK){
    ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Error with toggle");
    return NGX_ERROR;
}
ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Handler is ok");

return NGX_OK;
}

The following code is executed to set the variable value:

ngx_http_variable_value_t *var = ngx_pcalloc(r->pool, sizeof(ngx_http_variable_value_t));
var = ngx_http_get_indexed_variable(r, index);

if( #condition ){
    ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Redirected for:  %s", var_name.data);
    var->len = 2;
    var->data = (unsigned char *)"on";
}else{
    ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Not redirected for:  %s", var_name.data);
    var->len = 3;
    var->data = (unsigned char *)"off";
}

The logs return good values and "ok". But NGINX never returns any response.

status pending on chrome

Did I miss one part about NGX_HTTP_SERVER_REWRITE_PHASE handlers? Do you have a better idea how to update variables with the value of the requests?

Thank you for your answers.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

In ngx_int_t ngx_http_toggle_handler try to return NGX_DECLINED (not NGX_OK), it helped me to get response.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!