文章信息

Tomcat HTTP永久(301)重定向到HTTPS配置

发布时间:『 2017-08-12 05:50』  文章类别:系统运维  阅读(3873) 评论(1)

我的服务容器使用的是Tomcat8,也配置了HTTPS,前不久Tomcat的conf下web.xml配置了HTTP重定向到HTTPS配置。


在conf/server.xml中配置Connector 443端口的证书和密码等信息,这个关于证书配置这里不详说。


配置好后,配置http强制重定向到https,在conf/web.xml文件的</welcome-file-list>后面加上这样一段

<!-- Authorization setting for SSL -->

<login-config>
<auth-method>CLIENT-CERT</auth-method>
<realm-name>Client Cert Users-only Area</realm-name>
</login-config>
<security-constraint>
<web-resource-collection >
<web-resource-name >SSL</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>


保存后,服务会重启,重启后不出意外的话http就会直接跳转到https了。


但是,在百度站长工具里验证https网站认证提交后发现提交验证失败,其提交失败的原因是“非301重定向”,即从http://www.zeal.name重定向到https://www.zeal.name重定向代码不是301,使用浏览器开发工具的网络抓包发现这个重定向是302。


经过搜索查询发现302是临时重定向,百度、谷歌等搜索引擎不认定这是个全站开启https的网站,如果是301重定向,搜索引擎则认定为该重定向是永久的了,网络蜘蛛抓取的比重会高一些。


于是,这个302状态转301状态设置势在必得,经过百度搜索Tomcat配置http301转https发现竟然没有任何可参考的资源,真是绝人之路。


经过两个小时的测试修改,其中也想过使用urlrewritefilter 301配置重定向,结果发现urlrewritefilter重定向的主要是用到host重定向。实在没办法,于是你懂的满世界找,谷歌搜索发现在https://stackoverflow.com上还真的发现有这样的问题和答案。  


发现重定向的状态码在Realm配置,Realm中有属性transportGuaranteeRedirectStatus可以配置指定的重定向状态码,真是天无绝人之路。

 <Realm className="org.apache.catalina.realm.LockOutRealm" transportGuaranteeRedirectStatus="301">
    <!-- This Realm uses the UserDatabase configured in the global JNDI
         resources under the key "UserDatabase".  Any edits
         that are performed against this UserDatabase are immediately
         available for use by the Realm.  -->
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
           resourceName="UserDatabase" />
  </Realm>

配置transportGuaranteeRedirectStatus="301"后,重启Tomcat,访问网站,抓包发现终于发现重定向状态码由302变成了301。再去百度站长工具提交验证,两分钟后发现验证成功了。


后来查看Tomcat 6系列没有这个属性,Tomcat 7、8系列含有这个属性,估计国内开发者使用这个配置的少吧,现在应该会使用nginx来代理配置了。


【参考资料】

1.Perform 301 redirect from http to https in Apache Tomcat

2.Apache Tomcat 8 Configuration Reference

关键字:  tomcat  https  重定向  301  http
评论信息
1楼    210.13.50.170:作者好文 转走了。      [ 2021-07-21 03:44 ]
发表评论
验证码: 
当前时间
小主信息

愿历尽千帆,归来仍少年。
3D标签云

Anything in here will be replaced on browsers that support the canvas element

友情链接

Copyright ©2017-2024 uzen.zone
湘ICP备17013178号-3