请求头参数带下划线,后端无法接收(underscores_in_headers)

如果在请求头中有下划线的参数时,nginx则会默认屏蔽此头信息。


比如 access_token 之类的想用来做身份认证时,就不能用下划线,要用中线 – 替代。

可以在server{}段中添加参数,允许下划线,但是不推荐:

underscores_in_headers on;

这样nginx就会接受带下划线的请求头(nginx默认配置是off)。

提及此原因的说明在此:
https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/?highlight=underscores#missing-disappearing-http-headers
Missing (disappearing) HTTP Headers
If you do not explicitly set underscores_in_headers on;, NGINX will silently drop HTTP headers with underscores (which are perfectly valid according to the HTTP standard).
This is done in order to prevent ambiguities when mapping headers to CGI variables as both dashes and underscores are mapped to underscores during that process.

使用ipip地址库屏蔽城市

ipdb和geoip2模块非常相似,前者为国内公司做的ip地址库,后者为国外搞的。不过免费版都不是非常精准。
模块地址:https://github.com/vislee/ngx_http_ipdb_module

[root@MiWiFi-RA69-srv ~]# yum install json-c json-c-devel
nginx编译时加上参数:
--add-module=/home/ngx_http_ipdb_module-master

去ipip.net下载免费版的地址库文件(https://www.ipip.net/product/ip.html#ipv4city)
最后更新时间是2019年7月,版本还是挺老了。

以下部分在http{}段配置:

ipdb /home/www/ipipfree.ipdb;
ipdb_language CN;

# 定义map
map $ipdb_city_name $allowed_city {
default yes;
"北京" no;
"上海" no;
}

以下部分在server{}段配置:

server
{
    listen 80;
    server_name www.test.com;
    index index.html;
    root /home/www/www.test.com;

	location /
	{	
		if ($allowed_city = "no")
		{
		  return 403;
		}
	}
	
	# 提供一个查询接口
	location /ip
	{
		# ipdb_specifies_addr $http_addr;
		# ipdb_language EN;
		default_type application/html;
		add_header Content-Type "text/plain;charset=utf-8";
		return 200 "country_name:$ipdb_country_name, city_name:$ipdb_city_name,raw_info:$ipdb_raw";
	}
		
    access_log  off;
    error_log  /dev/null;
}

关于模块中更多的内置变量,可以去看github中文档。