强制使用https访问

环境:

tomcat8

jsp


准备:

1.产生密匙

参数中,-alias如果不用tomcat ,server.xml中需要另外加字段指明

秘钥库密码如何和秘钥密码不同和话,下面配置的时候需要分别加一下,网上的例子好多都是密匙库和秘钥密码相同

keytool -genkeypair -keyalg "RSA" -keystore "tomcat_keystore" -alias "tomcat"


2.在server.xml里配置密匙信息和https connector

只要把8443那个connector 解除注释就可以了,然后加上

keystoreFile="d:/key/tomcat.keystore" keystorePass="tomcat123"

那个protocal好像有几种选择,完整版

	<Connector port="443" protocol="HTTP/1.1"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" 
               keystoreFile="d:/key/tomcat.keystore" keystorePass="tomcat" />


下面是具体可以配置的选项,copy自:http://127.0.0.1/docs/config/http.html#SSL_Support(tomcat自带的文档)

The BIO, NIO and NIO2 connectors use the following attributes to configure SSL:
AttributeDescription
algorithm

The certificate encoding algorithm to be used. This defaults to KeyManagerFactory.getDefaultAlgorithm() which returns SunX509 for Sun JVMs. IBM JVMs return IbmX509. For other vendors, consult the JVM documentation for the default value.

allowUnsafeLegacyRenegotiation

Is unsafe legacy TLS renegotiation allowed which is likely to expose users to CVE-2009-3555, a man-in-the-middle vulnerability in the TLS protocol that allows an attacker to inject arbitrary data into the user's request. If not specified, a default of false is used. This attribute only has an effect if the JVM does not support RFC 5746 as indicated by the presence of the pseudo-ciphersuite TLS_EMPTY_RENEGOTIATION_INFO_SCSV. This is available JRE/JDK 6 update 22 onwards. Where RFC 5746 is supported the renegotiation - including support for unsafe legacy renegotiation - is controlled by the JVM configuration.

ciphers

If specified and using ',' as a separator, only the ciphers that are listed and supported by the SSL implementation will be used. The ciphers are specified using the JSSE cipher naming convention. The special value of ALL will enable all supported ciphers. This will include many that are not secure. ALL is intended for testing purposes only.

The list can also use ':' as a separator, in that case it will use the OpenSSL syntax (see OpenSSL documentation for the list of ciphers supported and the syntax).

If not specified, a default (using the OpenSSL notation) of HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5 will be used.

Note that Java does treat the order in which ciphers are defined as an order of preference.

clientAuth

Set to true if you want the SSL stack to require a valid certificate chain from the client before accepting a connection. Set to want if you want the SSL stack to request a client Certificate, but not fail if one isn't presented. A false value (which is the default) will not require a certificate chain unless the client requests a resource protected by a security constraint that uses CLIENT-CERT authentication.

clientCertProvider

When client certificate information is presented in a form other than instances of java.security.cert.X509Certificate it needs to be converted before it can be used and this property controls which JSSE provider is used to perform the conversion. For example it is used with the AJP connectors, the HTTP APR connector and with the org.apache.catalina.valves.SSLValve. If not specified, the default provider will be used.

crlFile

The certificate revocation list to be used to verify client certificates. If not defined, client certificates will not be checked against a certificate revocation list.

keyAlias

The alias used to for the server certificate in the keystore. If not specified the first key read in the keystore will be used.

keyPass

The password used to access the server certificate from the specified keystore file. The default value is "changeit".

keystoreFile

The pathname of the keystore file where you have stored the server certificate to be loaded. By default, the pathname is the file ".keystore" in the operating system home directory of the user that is running Tomcat. If your keystoreType doesn't need a file use "" (empty string) for this parameter.

keystorePass

The password used to access the specified keystore file. The default value is the value of the keyPass attribute.

keystoreProvider

The name of the keystore provider to be used for the server certificate. If not specified, the list of registered providers is traversed in preference order and the first provider that supports the keystoreType is used.

keystoreType

The type of keystore file to be used for the server certificate. If not specified, the default value is "JKS".

sessionCacheSize

The number of SSL sessions to maintain in the session cache. Use 0 to specify an unlimited cache size. If not specified, a default of 0 is used.

sessionTimeout

The time, in seconds, after the creation of an SSL session that it will timeout. Use 0 to specify an unlimited timeout. If not specified, a default of 86400 (24 hours) is used.

sslEnabledProtocols

The comma separated list of SSL protocols to support for HTTPS connections. If specified, only the protocols that are listed and supported by the SSL implementation will be enabled. If not specified, the JVM default (excluding SSLv2 and SSLv3 if the JVM enables either or both of them by default) is used. The permitted values may be obtained from the JVM documentation for the allowed values for SSLSocket.setEnabledProtocols() e.g. Oracle Java 7. Note: There is overlap between this attribute and sslProtocol.

sslImplementationName

The class name of the SSL implementation to use. If not specified, the default of org.apache.tomcat.util.net.jsse.JSSEImplementation will be used which wraps JVM's default JSSE provider. Note that the JVM can be configured to use a different JSSE provider as the default.

sslProtocol

The the SSL protocol(s) to use (a single value may enable multiple protocols - see the JVM documentation for details). If not specified, the default is TLS. The permitted values may be obtained from the JVM documentation for the allowed values for algorithm when creating an SSLContext instance e.g. Oracle Java 7. Note: There is overlap between this attribute and sslEnabledProtocols.

trustManagerClassName

The name of a custom trust manager class to use to validate client certificates. The class must have a zero argument constructor and must also implement javax.net.ssl.X509TrustManager. If this attribute is set, the trust store attributes may be ignored.

trustMaxCertLength

The maximum number of intermediate certificates that will be allowed when validating client certificates. If not specified, the default value of 5 will be used.

truststoreAlgorithm

The algorithm to use for truststore. If not specified, the default value returned by javax.net.ssl.TrustManagerFactory.getDefaultAlgorithm() is used.

truststoreFile

The trust store file to use to validate client certificates. The default is the value of the javax.net.ssl.trustStore system property. If neither this attribute nor the default system property is set, no trust store will be configured.

truststorePass

The password to access the trust store. The default is the value of the javax.net.ssl.trustStorePassword system property. If that property is null, no trust store password will be configured. If an invalid trust store password is specified, a warning will be logged and an attempt will be made to access the trust store without a password which will skip validation of the trust store contents.

truststoreProvider

The name of the truststore provider to be used for the server certificate. The default is the value of the javax.net.ssl.trustStoreProvider system property. If that property is null, the value of keystoreProvider is used as the default. If neither this attribute, the default system property nor keystoreProvideris set, the list of registered providers is traversed in preference order and the first provider that supports the truststoreType is used.

truststoreType

The type of key store used for the trust store. The default is the value of the javax.net.ssl.trustStoreType system property. If that property is null, the value of keystoreType is used as the default.



3.确认输入https://127.0.0.1/可以正常访问(浏览器会有一个警告,点击继续访问就可以了)

另外,官方给的文档地址是:http://127.0.0.1/docs/ssl-howto.html



方案:

方法一:在相应的应用的web.xml中加入

<transport-guarantee>CONFIDENTIAL</transport-guarantee>

具体做法可能有不同,下面是采用FORM权限验证时的配置

	<security-constraint>
		<display-name>zzz</display-name>
		<web-resource-collection>
			<web-resource-name>xxx</web-resource-name>
			<!-- Define the context-relative URL(s) to be protected -->
			<url-pattern>/*</url-pattern>
			<!-- If you list http methods, only those methods are protected so -->
			<!-- the constraint below ensures all other methods are denied     -->
			<http-method>DELETE</http-method>
			<http-method>GET</http-method>
			<http-method>POST</http-method>
			<http-method>PUT</http-method> 
		</web-resource-collection>
		<auth-constraint>
			<!-- Anyone with one of the listed roles may access this area -->
			<role-name>gm</role-name>
		</auth-constraint>
		<user-data-constraint>
			<transport-guarantee>CONFIDENTIAL</transport-guarantee>
		</user-data-constraint>
    </security-constraint>

    <!-- Default login configuration uses form-based authentication -->
    <login-config>
      <auth-method>FORM</auth-method>
      <realm-name>yyy</realm-name>
      <form-login-config>
        <form-login-page>/login.jsp</form-login-page>
        <form-error-page>/error.jsp</form-error-page>
      </form-login-config>
    </login-config>
    <security-role>
      <role-name>gm</role-name>
    </security-role>
  
方法二:在jsp页面中加入重定向,定向到https页面

<%
	if (!"https".equalsIgnoreCase(request.getScheme()))
	{
		String url=request.getRequestURL().toString();
		url=url.replace("http://","https://");		
		response.sendRedirect(url);
	}
%>


参考:

1.http://biancheng.dnbcw.info/java/337001.html

2.http://wenku.baidu.com/link?url=-yRtvPa5FsBnpgZj8btd4rBodqAHhknqIjLA2lloOunHvsXxyDkYADtaN1bHsVsfiuoQJCECfUEPUhr35mpPiz_9zptqLmp6USRl62HyuqG

3.

<think>好的,我现在需要帮助用户了解如何配置Nginx强制重定向到HTTPS。用户已经提供了一些参考资料,我需要整合这些信息,并按照用户的要求生成详细的步骤。首先,我要确认用户的需求是详细的配置步骤,所以需要一步步指导,同时确保符合用户提到的引用格式和结构。 首先,根据引用[2],有两种方法:rewrite和return 301。用户提到推荐方法2,也就是使用301状态码,这可能是因为301是永久重定向,对SEO更友好,且效率更高。所以,我应该优先介绍这种方法。 接下来,我需要考虑配置的位置。根据引用[1],如果是编译安装或自定义配置,可能需要单独配置443端口的server块。而用户的问题是关于强制重定向,所以重点在80端口的配置,将HTTP请求重定向到HTTPS。同时,引用[3]提到配置冲突的问题,比如如果有多个server块监听80端口,可能会导致冲突,需要检查是否有重复的配置,尤其是server_name是否正确。 然后,步骤部分需要详细说明如何编辑配置文件,通常是在/etc/nginx/sites-available/或nginx.conf中添加或修改server块。需要提醒用户备份配置文件,测试配置是否正确,并重新加载Nginx。同时,常见问题如配置冲突、防火墙设置、端口监听状态等,需要根据引用[3]中的排查步骤来总结。 可能用户还会遇到问题,比如配置后不生效,这时候需要检查语法错误,使用nginx -t测试,以及检查是否有其他server块干扰。引用[3]中的例子显示,可能存在多个server块监听同一端口,导致冲突,这时候需要确保只有一个server块处理HTTP到HTTPS的重定向,其他server块可能需要调整。 最后,生成相关问题时要围绕Nginx配置、HTTPS、重定向相关问题,比如优化方法、SSL证书配置、测试方法等。确保问题与主题相关,帮助用户进一步了解相关知识。 总结步骤: 1. 编辑Nginx配置文件,添加server块监听80端口,使用return 301重定向。 2. 配置HTTPS的server块,监听443端口,并配置SSL证书。 3. 检查配置冲突,避免多个server块监听同一端口和域名。 4. 测试配置并重新加载Nginx。 5. 常见问题排查,如防火墙、端口占用、语法错误等。 需要确保引用正确,比如引用[2]中的两种方法,引用[3]中的配置冲突问题,引用[4]中的重定向目的。同时,按照用户的格式要求,使用中文回答,行内公式用$...$,独立公式用$$...$$,但在这个问题中可能不需要数学公式,但需要保持结构清晰,代码块正确。</think>### 如何配置Nginx强制重定向到HTTPS的详细教程 以下是配置Nginx强制将HTTP请求重定向到HTTPS的步骤,基于Nginx的`return 301`方法(推荐)和`rewrite`方法,并提供常见问题排查: --- #### **方法1:使用301状态码(推荐)** 1. **编辑Nginx配置文件** 打开Nginx的配置文件(通常位于`/etc/nginx/sites-available/default`或自定义配置文件),在监听80端口的`server`块中添加以下内容: ```nginx server { listen 80; server_name example.com www.example.com; # 替换为你的域名 return 301 https://$server_name$request_uri; # 强制重定向到HTTPS } ``` 此配置会将所有HTTP请求永久重定向到相同域名的HTTPS地址[^2]。 2. **配置HTTPS的server块** 确保已配置监听443端口的`server`块,并正确指定SSL证书路径: ```nginx server { listen 443 ssl; server_name example.com www.example.com; ssl_certificate /path/to/your/certificate.crt; # SSL证书路径 ssl_certificate_key /path/to/your/private.key; # 私钥路径 # 其他HTTPS相关配置... } ``` --- #### **方法2:使用rewrite指令** 如果更习惯使用`rewrite`,可替换`return 301`为以下内容: ```nginx server { listen 80; server_name example.com www.example.com; rewrite ^(.*)$ https://$host$1 permanent; # permanent等效于301状态码 } ``` 此方法通过正则表达式匹配所有请求路径并重定向。 --- #### **关键注意事项** 1. **避免配置冲突** - 检查是否有其他`server`块也监听80端口,并确保`server_name`唯一或优先级正确[^3]。 - 示例冲突配置: ```nginx server { listen 80; server_name example.com; # 静态文件服务等无关配置... } ``` 此类配置会与重定向规则冲突,需合并或删除重复配置。 2. **测试与重载配置** - 执行命令检查语法:`nginx -t` - 重载配置:`nginx -s reload` 3. **检查端口与防火墙** - 确认Nginx已绑定80端口:`netstat -tuln | grep 80` - 确保防火墙允许HTTP/HTTPS流量:`sudo ufw allow 80/tcp`和`sudo ufw allow 443/tcp`。 --- #### **常见问题排查** - **重定向失效** - 检查域名是否匹配`server_name`,或使用通配符`_`作为默认配置。 - 查看错误日志:`tail -f /var/log/nginx/error.log` - **SSL证书错误** - 确认证书路径正确,且私钥文件权限为600。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值