要在NGINX C代码中获取自定义的HTTP头的值,可以使用以下代码:

#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>

static ngx_int_t ngx_http_custom_header_handler(ngx_http_request_t *r) {
    ngx_table_elt_t *h;
    ngx_str_t header_name = ngx_string("X-Custom-Header");
    ngx_str_t header_value;

    h = ngx_http_get_module_ctx(r, ngx_http_custom_header_module);

    if (h) {
        header_value = h->value;
        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Custom Header Value: %V", &header_value);
    }

    return NGX_OK;
}

static char *ngx_http_custom_header(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
    ngx_http_core_loc_conf_t *clcf;

    clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
    clcf->handler = ngx_http_custom_header_handler;

    return NGX_CONF_OK;
}

static ngx_command_t ngx_http_custom_header_commands[] = {
    { ngx_string("custom_header"),
      NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS,
      ngx_http_custom_header,
      0,
      0,
      NULL },

    ngx_null_command
};

static ngx_http_module_t ngx_http_custom_header_module_ctx = {
    NULL,                                  /* preconfiguration */
    NULL,                                  /* postconfiguration */

    NULL,                                  /* create main configuration */
    NULL,                                  /* init main configuration */

    NULL,                                  /* create server configuration */
    NULL,                                  /* merge server configuration */

    NULL,                                  /* create location configuration */
    NULL                                   /* merge location configuration */
};

ngx_module_t ngx_http_custom_header_module = {
    NGX_MODULE_V1,
    &ngx_http_custom_header_module_ctx,    /* module context */
    ngx_http_custom_header_commands,       /* module directives */
    NGX_HTTP_MODULE,                       /* module type */
    NULL,                                  /* init master */
    NULL,                                  /* init module */
    NULL,                                  /* init process */
    NULL,                                  /* init thread */
    NULL,                                  /* exit thread */
    NULL,                                  /* exit process */
    NULL,                                  /* exit master */
    NGX_MODULE_V1_PADDING
};

要使用上述代码,需要在NGINX配置文件中添加以下行:

location / {
    custom_header;
}

这将在每个HTTP请求中触发ngx_http_custom_header_handler函数,并获取X-Custom-Header的值。你可以根据需要修改header_namengx_log_error函数的调用来适应你的需求

nginx 获取自定的http 头的值C代码怎么写

原文地址: http://www.cveoy.top/t/topic/iU9D 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录