Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC

报错如下:(浏览器页面的和控制台的)

Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC

 

Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC

 

原因分析:

翻译过来就是:在请求目标中发现无效字符。有效字符在RFC 7230和RFC 3986中定义。

百度看看:原来这是从7.0开始的高版本tomcat中的新特性:就是严格按照 RFC 3986规范进行访问解析,而 RFC 3986规范定义了Url中只允许包含英文字母(a-zA-Z)、数字(0-9)、-_.~4个特殊字符以及所有保留字符(RFC3986中指定了以下字符为保留字符:! * ’ ( ) ; : @ & = + $ , / ? # [ ])。

查看Tomcat官方文档:

Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC

Add additional checks for valid characters to the HTTP request line parsing so invalid request lines are rejected sooner。翻译过来就是:为HTTP请求行分析添加有效字符的附加检查,以便更快拒绝无效的请求行。

文档地址:http://tomcat.apache.org/tomcat-7.0-doc/changelog.html

 

解决方案:

既然知道原因了,那我们应该怎么解决这个问题呢?

网上的几种办法:

1、更换低版本的Tomcat。这个办法表面上是可行的,但是这不是属于自欺欺人嘛。因为在实际的项目开发中,你改动Tomcat很可能也要改动JDK版本和其他jar包版本,这会影响到整个项目的正常开发,没理由大家都跟着你改吧。所以pass掉了。

2、在Tomcat的安装目录中,打开conf/catalina.properties,找到末尾的一行。增加两行配置:

tomcat.util.http.parser.HttpParser.requestTargetAllow=|{}
org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true

其中,第一行|后面表示不检查的字符。

Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC

但是,运行后还是报错,查看控制台:

Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC

证明这几个字符都不允许这样的方式来逃避检查,即requestTargetAllow 只能配置|、{、} 允许这三个字符,对于其他的(例如" < > [ \ ] ^ ` { | } .),在请求时,仍然拦截。所以失败了嗷。

3、在Tomcat的安装目录中,打开conf/server.xml文件,找到<Connector>节点,增加maxHttpHeaderSize="10240"这个属性,maxHttpHeaderSize默认是8*1024的,改为10*1024,用于增加请求头的长度。

Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC

保存运行,发现也没什么用。

4、最后,还是得看官方的文档。堵上了一扇门,必会有另外一扇窗。

Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC


文档地址:https://tomcat.apache.org/tomcat-8.5-doc/config/systemprops.html

官方提供了relaxedPathChars relaxedQueryChars 这两个属性用于解决这个问题。

那这两个属性怎么用呢?再看:

Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC

文档地址:https://tomcat.apache.org/tomcat-8.5-doc/config/http.html

只需在刚刚的<Connector>标签中,加入relaxedPathChars="|{}[],%" 和 relaxedQueryChars="|{}[],%"即可,其中|后面的字符可以自己随意增减。即:

Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC

保存运行,大功告成了。

 

思考总结:

1、遇到问题,先自己去看看能不能解决,不能的话再去网上查找资料。

2、官方文档很重要,一般的问题往往都可以在文档里面找到解决办法。

3、多学习学习英文。。。

4、这个搞了很久,最后还是一位大佬的博客解决了问题。十分感谢

链接:https://yq.aliyun.com/articles/641394#