日期:2014-05-16  浏览次数:20885 次

apache安装与配置重定向

1.apache安装

ubuntu下安装apache可以用命令:

sudo apt-get install apache2

安装完后,默认的apache目录是:

/etc/apache2

启动apache的命令可以是:

sudo /etc/init.d/apache2 restart 或者 service apache2 start


2.配置反向代理

在apache的apache2.conf主配置文件,include一个自己创建的httpd.conf文件

在里面写入以下内容:

    <IfModule mod_proxy.c>
        #Reverse Proxy(反向代理)  
        <Proxy *>
            Order Deny,Allow  
           #Deny from all  
            Allow from all
        </Proxy>

        ProxyRequests Off
        #proxy setting  
        ProxyPass           /webTest http://127.0.0.1:8080/webTest
        ProxyPassReverse    /webTest http://127.0.0.1:8080/webTest

    </IfModule>

这里的 proxyPass表示将/webTest 这样的请求转成http://127.0.0.1:8080/webTest
ProxyPassReverse,如果没有的时候,在没有重定向的情况能够很好的工作。
但一旦有重定向时(即服务器发送一个http响应,其中状态码为302,location为新的url,表示客户端浏览器应该重新请求这个location中的url)
如果没有设置ProxyPassReverse,这时客户端会请求到http://127.0.0.1:8080/webTest/x 这样的地址.

例子:
前端以apache作为http服务器,后端tomcat为servlet容器
我们最终目的需要将http://localhost/webTest这样的请求地址转成http://localhost:8080/webTest并发送到后端tomcat

  当前用户请求登录地址为http://localhost/webTest/jsp/login.jsp
  这里在有了上面的proxy反向代理配置后,apache将http://localhost/webTest/jsp/login.jsp替换成
http://localhost:8080/webTest/jsp/login.jsp
  接着我们登录,成功后,业务程序会发出一个重定向到首页index.jsp,这时我们注释掉上面配置的ProxyPassReverse
  可以看到浏览器的url被替换成了http://127.0.0.1:8080/webTest/jsp/index.jsp?username=youusername
  也就是服务器发送一个重定向指今的location为http://127.0.0.1:8080/webTest/jsp/index.jsp?username=jack
  这时,客户端可能无法访问你服务器内部的重定向地址(即127.0.0.1:8080/webTest/jsp/index.jsp?username=jack)
  所以我们需要去掉上面的ProxyPassReverse的注释,这样在重定向时,apache会将重定向的地址127.0.0.1:8080/webTest/jsp/index.jsp?username=jack
  转成127.0.0.1/webTest/jsp/index.jsp?username=jack作为location发送给客户端。
  客户端浏览器再作一个get请求,请求url为127.0.0.1/webTest/jsp/index.jsp?username=jack,
  这样apache又能够将请求映射到127.0.0.1:8080/webTest/jsp/index.jsp?username=jack内部地址。