Underscores in Headers When Using Nginx as a Reverse Proxy for IIS
Original Chinese title: iis使用nginx做反向代理,下划线问题
Solution
- If you’re in the same boat as me—a bunch of internal IIS servers on the intranet, but only one public IP facing the outside—this setup is worth considering.
- For the specific configuration, I followed this guide: IIS Server Clustering (Nginx Approach).
The Nginx Underscore Issue
-
Static assets like HTML, JS, and CSS all worked without a hitch, yet a few RESTful API requests on the site simply refused to go through. Time to check Nginx’s
error_log:client sent invalid request while reading client request line -
After looking it up online, I found that Nginx restricts characters in HTTP header names—if a header name contains an underscore, it gets ignored.
-
Sure enough, the failing APIs all had underscores in their headers. There are two ways around this: the brute-force approach is to redesign the APIs and remove the underscores.
-
Or, as some suggest, you can check the Nginx source behavior and toggle the config directive:
In the ngx_http_parse_header_line() function: f (ch == ‘_’) { if ( allow_underscores // where the issue lies ) Enable underscores_in_headers on This can be added inside the http or server block. Syntax: underscores_in_headers on|off Default: off Context: http, server Determines whether underscores are allowed in header field names
That’s Pretty Much It
方案
- 如果你和我一样,大量内网的iis服务器,但是对外只有一个ip,可以考虑这样的解决方案。
- 具体解决我参照如下的解决 IIS server集群(nginx方案)。
nginx下划线的问题
-
html,js,css都是相当的顺利,网站里面有几个restful 的API请求打死都过不去。只能查nginx error_log
client sent invalid request while reading client request line -
网上查了一下,发现是nginx对header name 字符做了限制,如果header name 中包含下划线,则忽略掉。
-
确实几个无法访问的API都是带了下划线的。有两个解决方案,最粗暴的就是重定义下接口,去掉那些下划线。
-
当然还有给出改nginx源码的方法
在ngx_http_parse_header_line() 函数中 f (ch == ‘_’) { if ( allow_underscores // 问题所在 ) 开启 underscores_in_headers on 可以加到http或者server中。 语法:underscores_in_headers on|off 默认值:off 使用字段:http, server 是否允许在header的字段中带下划线