Nginx C 代码:获取自定义 HTTP 头部值
要在 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_name
和 ngx_log_error
函数的调用来适应你的需求。
注意:
- 此代码示例假设你已经具备 Nginx 模块开发的基础知识。
ngx_log_error
函数将错误信息写入 Nginx 错误日志。- 你可以根据自己的需求修改
header_name
和ngx_log_error
函数的调用。

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