Tomcat调优
· 阅读需 5 分钟
隐藏版本号
进入tomcat的lib目录找到catalina.jar文件
unzip catalina.jar
之后会多出两个文件夹
进入org/apache/catalina/util编辑配置文件ServerInfo.properties
修改为
server.info=Apache Tomcat
server.number=0.0.0.0
server.built=Nov 7 2016 20:05:27 UTC
将修改后的信息压缩回jar包
cd /tomcat/lib
jar uvf catalina.jar org/apache/catalina/util/ServerInfo.properties
禁用不安全的方法
tomcat限制不安全http方法,如put、delete等等,设置方法在conf/web.xml里添加限制如下格式:
<security-constraint>
<web-resource-collection>
<url-pattern>/*</url-pattern>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
<http-method>HEAD</http-method>
<http-method>OPTIONS</http-method>
<http-method>TRACE</http-method>
</web-resource-collection>
<auth-constraint>
</auth-constraint>
</security-constraint>
错误页面跳转
tomcat的404、502、403等等错误页面的跳转设置为指定跳转页面,设置方法在conf/web.xml里添加跳转如下格式:
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/404.html</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
<error-page>
<error-code>400</error-code>
<location>/404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/404.html</location>
</error-page>
使tomcat支持软链接
修改conf/context.xml文件:
tomcat7配置方法:
<!-- The contents of this file will be loaded for each web application -->
<Context allowLinking="true">
tomcat8配置方法:
<Context>
<Resources allowLinking="true" />
</Context>
tomcat增加http安全响应头
修改web.xml文件:
配置方法:
<filter>
<filter-name>httpHeaderSecurity</filter-name>
<filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>antiClickJackingEnabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>antiClickJackingOption</param-name>
<param-value>SAMEORIGIN</param-value>
</init-param>
<init-param>
<param-name>blockContentTypeSniffingEnabled</param-name>
<param-value>false</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>httpHeaderSecurity</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
禁用管理端,强制或使用nginx配置规则
- 删除默认的Tomcat安装目录/conf/tomcat-users.xml文件(强制)
- 删除Tomcat安装目录/webapps下默认的所有目录和文件(强制)
Server header重写
当tomcat HTTP端口直接提供web服务时此配置生效,加入此配置,将会替换http响应Server header部分的默认配 置,默认是Apache-Coyote/1.1
修改conf/server.xml:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
server="webserver" />
访问日志规范
开启Tomcat默认访问日志中的Referer和User-Agent记录,一旦出现安全问题能够更好的根据日志进行问题排查;
X-Forwarded-For用于nginx作为反向代理服务器时,获取客户端真实的IP
修改conf/server.xml:
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%{X-Forwarded-For}i %l %u %t %r %s %b %{Referer}i %{User-Agent}i %D" resolveHosts="false" />
tomcat设置字符集UTF-8
修改conf/server.xml:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8" />