實驗前提:準備三臺虛擬機,如果是在windows上安裝的vmware 真實機也可以作爲其中一臺使用
squid服務器IP:192.168.4.103
WEB服務器IP :192.168.4.200
客戶機IP :192.168.4.254
實驗一:傳統代理
squid服務器上操作
yum -y install squid
vim /etc/squid/squid.conf
visible_hostname squid.tarena.com
cache_dir ufs /var/spool/squid 100 16 256
iptables -t nat -I PREROUTING -i eth1 -s 192.168.4.0/24 -p tcp --dport 80 -j REDIRECT --to-ports 3128
iptables -t nat -nL 查看規則是否生效
web服務器上的操作
yum -y install httpd
service httpd start
chkconfig httpd on
echo helloword > /var/www/html/index.html
在客戶機瀏覽器上配置代理
例如:火狐瀏覽器
選項--高級--鏈接設置--手動配置代理
輸入:192.168.4.103
端口:3128
地址欄輸入web服務器ip驗證是否能訪問
如果是在虛擬機上驗證可以直接用命令
curl http://192.168.4.200 (web服務IP)
實驗二:透明代理
給squid添加一個網卡 網卡IP設置爲:172.16.0.1
web服務器添加一個網卡 IP設置爲:172.16.0.2
#vim /etc/squid/squid.conf
http_access allow all
http_port 3128 transparent
網關設置轉發 #iptables 語法格式
#iptables -t 表名 -I 鏈 條件 -J 結果
設置防火牆規則
#iptables -t nat -I PREROUTING -i eth1 -s 192.168.4.0/24 -p tcp --dport 80 -j REDIRECT --to-ports 3128
查看防火牆規則
iptables -t nat -nL
設置網關 vim /etc/sysconfig/network-scripts/ifcfg-eth0
GATEWAY=192.168.4.103
客戶機驗證;curl http://172.16.0.2 【web服務器新添加的網卡IP】
實驗三:反向代理
squid服務器上必須關閉httpd 否則端口衝突服務不能正常啓動
srvice httpd stop
清空實驗二的iptables規則
iptables -t nat -F
vim /etc/squid/squid.conf
http_port 80 vhost
cache_peer 172.16.0.2 parent 80 0 originserver
cache_peer 172.16.0.1 parent 80 0 originserver
service squid restart
客戶機驗證:
curl http://代理服務器IP地址
實驗四:基於虛擬主機的代理
web服務器上的操作
vim /etc/httpd/conf/httpd.conf
#NameVirtualHost..*:80 刪除該行的註釋符號“#”
<VirtualHost *:80>
DocumentRoot /var/www/web1
ServerName www.baidu.com
<VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/web2
ServerName bbs.baidu.com
<VirtualHost>
分別在兩個路徑文件/var/www/web1 && /var/www/web2 下創建兩個網站首頁:web1 , web2 並給首頁文件輸入內容
mkdir /var/www/{web1,web2}
echo “www” > /var/www/web1/index.html
echo “bbs” > /var/www/web2/index.html
vim /etc/hosts
192.168.4.200 www.baidu.com bbs.baidu.com
修改squid配置文件
cache_peer 192.168.2.2 parent 80 0 originserver name=www
cache_peer 192.168.2.2 parent 80 0 originserver name=bbs
cache_peer_domain www www.tarena.com
cache_peer_domain bbs bbs.tarena.com
因爲這裏沒有配置DNS服務 所以客戶機上需要指定域名解析
vim /etc/hosts
192.168.4.103 www.baidu.com bbs.baidu.com
客戶機驗證:
[root@monitor ~]# curl http://www.baidu.com
www.baidu.com
[root@monitor ~]# curl http://bbs.baidu.com
bbs.baidu.com
注意:添加網卡第二個eth1時需要更改網卡在/etc/sysconfig/network-scripts/ifcfg-eth1的HWADDR與物理地址一致(本人是直接複製的ifcfg-eth0 所以曾在此處出錯)重啓network時提示找不到設備eth1
ifconfig eth1
eth1 Link encap:Ethernet HWaddr 00:0C:29:85:52:C6
[root@slave200 web2]# vim /etc/sysconfig/network-scripts/ifcfg-eth1
HWADDR=00:0C:29:85:52:C6