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.
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.
In ngx_int_t ngx_http_toggle_handler try to return NGX_DECLINED (not NGX_OK), it helped me to get response.