前面一个帖子《Windows下配置Apache、PHP、MySQL环境》教会了我们在Windows环境下
独立配置Apache、PHP、MySQL环境,配置好之后我们可以使用http://localhost访问根目录了。
但是,假如我们有多个项目的时候,只能通过http://localhost/project1/
和 http://localhost/project2/ 分别访问项目1和项目2,而这样无法最好地重现
线上版本服务器环境(线上服务器环境一般是一级域名,假设是http://test.com),
而这里的http://localhost/project1/是二级域名,当你的项目中使用相对路径,
此时,会出现效果不一致。
http://localhost/project1/ 下面的这个地址将访问http://localhost/js/test.js
(错误,应该是http://localhost/project1/js/test.js才对)
http://test.com下面的这个地址将访问http://test.com/js/test.js(正确)
因此,为了避免这种情况,同时方便访问,我们定制本地的虚拟域名。
定制虚拟域名涉及两处:
1、虚拟域名配置文件httpd-vhosts.conf
2、hosts文件
1、httpd-vhosts.conf文件的配置如下:
###开始
NameVirtualHost *:80
<VirtualHost *:80>
ServerName localhost
DocumentRoot "D:/WWW/WEB"
AllowEncodedSlashes On
<Directory "D:/WWW/WEB">
Options FollowSymLinks IncludesNOEXEC Indexes
DirectoryIndex index.php index.html
AllowOverride All
Order Deny,Allow
Allow from all
Require all granted
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]
</Directory>
</VirtualHost>
<VirtualHost *:80>
ServerName www.test.com
ServerAlias test.com
DocumentRoot "D:/WWW/WEB/test"
AllowEncodedSlashes On
<Directory "D:/WWW/WEB/test">
Options FollowSymLinks IncludesNOEXEC Indexes
DirectoryIndex index.php index.html
AllowOverride All
Order Deny,Allow
Allow from all
Require all granted
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]
</Directory>
</VirtualHost>
###结束
2、hosts配置如下:
127.0.0.1 localhost
127.0.0.1 www.test.com
127.0.0.1 test.com
配置完成之后,重启Apache服务器,然后访问http://test.com即可。
下面介绍一下httpd-vhosts.conf里面的一些参数:
(1)NameVirtualHost *:80
新版已经移除,旧版中,虚拟域名的标签必须依赖它存在
(2)<VirtualHost *:80>
指定虚拟域名的ip或域名,后面是端口,*表示匹配所有ip或域名
(3)ServerName www.test.com
虚拟域名
(4)ServerAlias test.com
虚拟域名别名,表示访问test.com的时候实际访问www.test.com,可以多个
(5)DocumentRoot "D:/WWW/WEB"
虚拟域名根目录,有些人使用\作为分界符,当\在最后时候,
会导致"被转义导致错误,
即"D:\WWW\WEB\" 会报错,改 "D:\WWW\WEB\\"
或 "D:\WWW\WEB" 都行
(6)AllowEncodedSlashes On
缺少时,当%2F作为路径会导致Object not found
错误情形:
http://localhost/index.php/test/a%2Fb 访问失败
http://localhost/index.php?test=a%2Fb 访问成功
(7) <Directory "D:/WWW/WEB">
这里路径同DocumentRoot 即可,它表示对该目录的一些属性进行设置
(8) Options FollowSymLinks IncludesNOEXEC Indexes
FollowSymLinks:服务器允许在此目录中使用符号连接
IncludesNOEXEC :允许服务器端包含,但禁用”#exec cmd”和”#exec cgi”。
Indexes:当没有DirectoryIndex 指定文件时,列举目录内容
(9) DirectoryIndex index.php index.html
默认文件访问顺序,如果同时有index.php和index.html,则优先访问index.php
(10) AllowOverride All
Apache重定向必需
(11) Order Deny,Allow
Allow from all
访问控制,这里配置允许所有访问,使用deny from all 则禁止所有的访问
(12) RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]
TRACE和TRACK是用来调试web服务器连接的HTTP方式.支持该方式的服务器存在跨站脚本漏洞
(13) 其他补充
vhosts的部分配置可以在.htaccess覆盖,比如:
vhosts中的配置的是Allow from all,.htaccess中配置的是Deny from all,
则当前目录是Deny生效。
如果需要跨目录配置虚拟主机,需要加入:
Require all granted
未经同意禁止转载!
转载请附带本文原文地址:Apache配置虚拟域名,首发自 Zjmainstay学习笔记




