一.什么是VirtualHost?
简单一句话VirtualHost就是用来解决一个apache服务映射多个域名的。比如对于img.3renyou.com 我们希望映射到 /var/www/httpdocs/img/
对于 www.3renyou.com 我们希望映射到 /var/www/httpdocs/app/ 这样通过二级域名来做不同的分离。
二. 如何配置VirtualHost?
对于VirtualHost,ubuntu和redhat是不同的,这里说说ubuntu的配置方式:
1. 打开目录 /etc/apache2/sites-available/, 发现 default 和 default-ssl 两个文件, 其中 default 是 http 虚拟主机服务的配置文件, default-ssl 是配置 https 服务使用的. 可以复制一份 default 文件. 并修改配置文件名, 文件名必须与域名一致 (如: demo.aliluna.com)
2. 打开新建的配置文件, 修改 DocumentRoot, ServerName 和对应的配置目录. 例子如下:
# # DocumentRoot 是网站文件存放的根目录 # ServerName 是网站域名, 需要跟 DNS 指向的域名一致 # <VirtualHost *:80> ServerAdmin [email protected] DocumentRoot /var/www/httpdocs/demo_aliluna_com ServerName demo.aliluna.com ErrorLog ${APACHE_LOG_DIR}/demo.aliluna.com-error.log CustomLog ${APACHE_LOG_DIR}/demo.aliluna.com-access.log combined </VirtualHost>
3. 通过 a2ensite 激活虚拟主机配置
sudo a2ensite demo.aliluna.com
4. 打开目录 /etc/apache2/sites-enabled/, 你会发现所有激活的虚拟主机, 可以通过 a2dissite 进行注销
sudo a2dissite demo.aliluna.com
5. 注意在httpd.conf加上:
NameVirtualHost *:80
6. 重启 Apache 服务, 激活虚拟主机
sudo /etc/init.d/apache2 restart
配置好VirtualHost之后,我们就解决了img.3renyou.com和www.3renyou.com分离。但还没解决端口映射问题,我们需要对访问www.3renyou.com的所有请求让他转发到tomcat,这可以通过proxy_http方式。
二。配置proxy_http
1.激活mod_proxy
cd /etc/apache2/mods-available
sudo a2enmod proxy_http
2.配置mod_proxy
修改/etc/apache2/sites-available/www.3renyou.com
加入
ProxyPass / http://localhost:8781/
ProxyPassReverse / http://localhost:8781/
最基本的配置就是这样了,对于其他 apache配置项后续再新开博文。
参考:http://www.neoease.com/apache-virtual-host/
后续问题:
1. 遇到一次按照上面配置但没有效果,原因是http.conf没有加入:
Include /etc/apache2/sites-enabled/
2. 遇到一个cookie没有带过来的问题
需要配置ProxyPassReverseCookieDomain:
<VirtualHost *:80>
ServerName www.zhangyutai.com
ProxyPass / http://localhost:8080/
ProxyPassReverse / http://localhost:8080/
ProxyPassReverseCookieDomain localhost zhangyutai.com
ProxyPassReverseCookiePath / /
</VirtualHost>