同一个应用下面多个域名直接跳转

目标:一级域名登陆之后二级域名同样会获取用户信息。

Tomcat 下,不同的二级域名,Session 默认是不共享的,因为 Cookie 名称为 JSESSIONID 的 Cookie 根域是默认是没设置的,访问不同的二级域名,其 Cookie 就重新生成,而 session 就是根据这个 Cookie 来生成的,所以在不同的二级域名下生成的 Session 也不一样

tomcat7 + jsp +nginx

查阅各种资料之后总结如下:

>配置nginx 映射成不同的域名。

一级域名:http://www.testxmf.com/

>二级域名:http://tool.testxmf.com 、 http://traffic.testxmf.com

配置tomcat server.xml

<Engine name="Catalina" defaultHost="localhost">

<!--For clustering, please take a look at documentation at:

/docs/cluster-howto.html  (simple how to)

/docs/config/cluster.html (reference documentation) -->

<!--

<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>

-->

<!-- Use the LockOutRealm to prevent attempts to guess user passwords

via a brute-force attack -->

<Realm className="org.apache.catalina.realm.LockOutRealm">

<!-- 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.  -->

<Valve className="org.three3s.valves.CrossSubdomainSessionValve"/>

<Realm className="org.apache.catalina.realm.UserDatabaseRealm"

resourceName="UserDatabase"/>

</Realm>

<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true" xmlNamespaceAware="false" xmlValidation="false">

<!-- SingleSignOn valve, share authentication between web applications

Documentation at: /docs/config/valve.html -->

<!--

<Valve className="org.apache.catalina.authenticator.SingleSignOn" />

-->

<!-- Access log processes all example.

Documentation at: /docs/config/valve.html

Note: The pattern used is equivalent to using pattern="common" -->

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"

prefix="localhost_access_log." suffix=".txt"

pattern="%h %l %u %t %r %s %b %T" />

<Context path=""  docBase="/home/wsm/website" reloadable="true" crossContext="true" sessionCookiePath="/" sessionCookieDomain=".testxmf.com"></Context>

</Host>

</Engine>

tomcat lib下加入CrossSubdomainSessionValve.jar 这个包

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;

import org.apache.catalina.Globals;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.ServerCookie;

/**
 * 取代由 Tomcat 域产生的会话 cookie ,允许该会话 cookie 跨子域共享。
 *
 * Tomcat Server.xml 配置:
 * <Valve className="me.seanchang.CrossSubdomainSessionValve"/>
 */
public class CrossSubdomainSessionValve extends ValveBase {
	private static Logger log = Logger.getLogger("CrossSubdomainSessionValve");
	public CrossSubdomainSessionValve() {
		super();
		info = "me.seanchang.CrossSubdomainSessionValve/1.0";
	}

	@Override
	public void invoke(Request request, Response response) throws IOException,
			ServletException {
		// this will cause Request.doGetSession to create the session cookie if
		// necessary
		request.getSession(true);

		// replace any Tomcat-generated session cookies with our own
		Cookie[] cookies = response.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];

				log.info("CrossSubdomainSessionValve: Cookie name is "
						+ cookie.getName());
				if (Globals.SESSION_COOKIE_NAME.equals(cookie.getName()))
					replaceCookie(request, response, cookie);
			}
		}

		// process the next valve
		getNext().invoke(request, response);
	}

	/**
	 * @param request
	 * @param response
	 * @param cookie
	 * cookie to be replaced.
	 */
	protected void replaceCookie(Request request, Response response, Cookie cookie) {
		// copy the existing session cookie, but use a different domain
		Cookie newCookie = new Cookie(cookie.getName(), cookie.getValue());
		if (cookie.getPath() != null)
			newCookie.setPath(cookie.getPath());
			newCookie.setDomain(getCookieDomain(request));
			newCookie.setMaxAge(cookie.getMaxAge());
			newCookie.setVersion(cookie.getVersion());
		if (cookie.getComment() != null)
			newCookie.setComment(cookie.getComment());
			newCookie.setSecure(cookie.getSecure());

		// if the response has already been committed, our replacement strategy
		// will have no effect
		MimeHeaders headers = new MimeHeaders();
		if (response.isCommitted())

			log.info("CrossSubdomainSessionValve: response was already committed!");
			// find the Set-Cookie header for the existing cookie and replace its
			// value with new cookie
			headers = response.getCoyoteResponse().getMimeHeaders();
			for (int i = 0, size = headers.size(); i < size; i++) {
				if (headers.getName(i).equals("Set-Cookie")) {
					MessageBytes value = headers.getValue(i);
					if (value.indexOf(cookie.getName()) >= 0) {
						StringBuffer buffer = new StringBuffer();
						ServerCookie
								.appendCookieValue(buffer, newCookie.getVersion(),
										newCookie.getName(), newCookie.getValue(),
										newCookie.getPath(), newCookie.getDomain(),
										newCookie.getComment(),
										newCookie.getMaxAge(),
										newCookie.getSecure(), true);

						log.info("CrossSubdomainSessionValve: old Set-Cookie value: "
								+ value.toString());
						log.info("CrossSubdomainSessionValve: new Set-Cookie value: "
								+ buffer);
						value.setString(buffer.toString());
					}
				}
			}
	}

	/**
	 * @param request provides the server name used to create cookie domain.
	 * @return the last two parts of the specified request's server name preceded by a dot.
	 */
	protected String getCookieDomain(Request request) {
		String cookieDomain = request.getServerName();
		String[] parts = cookieDomain.split("\\.");
		if (parts.length >= 2)
			cookieDomain = parts[parts.length - 2] + "."
					+ parts[parts.length - 1];
		return "." + cookieDomain;
	}

	public String toString() turn ("CrossSubdomainSessionValve[container=" + container.getName() + ']');
	}
}

转自:http://497155382.blog.163.com/blog/static/1949123201391694020/

http://tomcat.apache.org/tomcat-6.0-doc/config/context.html

时间: 2024-10-10 21:53:28

同一个应用下面多个域名直接跳转的相关文章

apache域名301跳转和访问控制的优先级

apache域名301跳转和访问控制的优先级 实验背景:apache虚拟主机有两个域名 111.com 222.com 其中222.com 访问的时候跳转到111.com,并且给该虚拟主机做了访问控制,只允许127.0.0.1访问.问题:当访问222.com时,它是先跳转到111.com,还是直接403呢? 打开apache中虚拟主机配置文件: vim /usr/local/apache2/conf/extra/httpd-vhosts.conf,可以看到当前配置如下(没做访问控制措施): 我们

域名301跳转

一个网站难免会有多个域名,而多个域名总得有一个主次.只要定义好了主域名,不管用哪个域名都会跳转到主域名上来.那么这个行为就叫做域名跳转,也可以叫重定向,这里的301只是一个状态码.跳转除了301还有302.301是永久重定向(域名跳转用301):302是临时重定向. [[email protected] www]# vim /usr/local/apache2/conf/extra/httpd-vhosts.conf 在对应的虚拟主机配置文件中加入 <IfModule mod_rewrite.c

Apache配置域名301跳转

配置域名301跳转 在有两个域名的情况下我们需要设置一个主域名(将次域名跳转到主域名下),操作命令如下: vim /usr/local/apache2/conf/extra/httpd-vhosts.conf 在 # CustomLog "logs/dummy-host.example.com-access_log" common下面一行添加如下: <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTP_HO

nginx域名隐性(地址栏域名不变)跳转

1.完全url的域名隐性跳转 server_name a.b.com location / { proxy_pass http://x.y.com; } 效果:浏览器地址栏中输入a.b.com域名不变访问的内容为x.y.com上的内容 2.部分url的域名隐性跳转到非根目录下的内容 server_name a.b.com location ~ .*\.(js|css)$ { rewrite ^/(.*) /js/$1 break; proxy_pass http://x.y.com break;

LAMP 1.9域名301跳转

给两个域名分主次.输入次域名跳转到主域名然后进行访问. 首先打开虚拟机配置文件. vim /usr/local/apache2/conf/extra/httpd-vhosts.conf 把这段配置添加到配置文件里 <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTP_HOST} ^www.wang.com$ RewriteRule ^/(.*)$ http://www.denny.com/$1 [R=301,L] </I

域名301跳转---模块

1.编辑虚拟主机文件 vim /usr/local/apache2/conf/extra/httpd-vhosts.conf 加入: 跳转模块: <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTP_HOST} ^www.jz.com$       ------要跳转的条件 RewriteRule ^/(.*)$ http://www.xrc.com/$1 [R=301,L]------调到哪里 </IfModule&g

httpd之域名301跳转

一个站点有多个域名,但要分主次,所以用301来永久跳转,302表示临时跳转. 方法一.rewrite,涉及模块mod_rewrite <IfModule mod_rewrite.c>        RewriteEngine on        RewriteCond %{HTTP_HOST} !^www.sunnysky.com$ RewriteRule ^/(.*)$ http://www.sunnysky.com/$1 [R=301,L]</IfModule> 或者 <

在同一个服务器(同一个IP)为不同域名绑定的免费SSL证书

越来越多的浏览器不在支持http协议了,这就要求你为你的网站必须绑定SSL证书.谷歌浏览器也将要在今年取消对http协议的支持,申请CA证书迫在眉睫.我购买有两个域名,一个虚拟机,没事鼓捣鼓捣,图个乐趣.在阿里云申请了免费证书,一直用的好好的.这次过年恰遇证书更新,想一起把所有域名都升级到https.购买两个证书分别绑定域名.顺带说一下如何阿里云购买免费域名,现在已经不太容易找到免费域名购买按钮了. [动图示意购买免费CA] 购买完成,并分别绑定www.a.com和www.b.com 后,访问a

Apache环境利用.htaccess文件设置域名301跳转(不带www跳转到带www)

相信很多站长朋友都遇见过这样的问题,即带www的域名与不带www的域名同时都被收录,但域名权重情况差距很大.这问题主要是由于搜索引擎把这两个域名当做两个不同网站看待,导致一个域名被判定是镜像网站造成的.毫无疑问,不管是带www还是不带www,唯一域名能够给你的网站带来更多的好处.这样无论是用户还是搜索引擎,都会记住你网站的唯一域名,也不会造成搜索引擎的误判而导致惩罚.下面本文就来介绍一下Apache环境下利用.htaccess文件设置301跳转,强制用户或搜索引擎重定向到唯一域名. #301重定