理解根目录与虚拟目录的关系
理解根目录与虚拟目录的关联:安装Apache后,打开httpd.conf配置文件,可见DocumentRoot默认指向apache安装目录下的htdocs文件夹。将网页文件置于该文件夹内即可测试,例如放入1.php后,通过http://127.0.0.1/1.php访问。若希望将网站存放于其他位置如F:/MyPHP,只需将DocumentRoot修改为F:/MyPHP,并将文件移入该目录,仍可通过相同URL访问。
虚拟目录本质上是真实目录的逻辑映射,二者存在区别。在真实目录中,若于F:/MyPHP下建Test文件夹并放入2.php,需通过http://127.0.0.1/Test/2.php访问。但出于安全或结构优化考虑,常需建立访问地址与实际文件夹名的映射关系。例如希望隐藏Test文件夹名,通过http://127.0.0.1/cmj/2.php访问实际位于Test中的2.php,此时因无cmj物理文件夹,需借助虚拟目录实现这种映射。
配置多虚拟目录
多虚拟目录配置
假设Apache安装于D:\Program Files\Apache2.2,端口设为8080,默认根目录为D:\Program Files\Apache2.2\htdocs。通常可在htdocs下建MySite文件夹,通过http://localhost:8080/MySite访问。若需将站点移至其他目录,如D盘新建的D:\Code\WebSite,并通过http://localhost:8080/DemoSite访问,则需配置虚拟目录。
编辑httpd.conf文件,定位至相关节点并在其中添加配置内容:
#下面是虚拟目录声明格式
#Alias用来定义虚拟目录及虚拟目录路径,其中虚拟目录名称用于URL访问的路径别名,可以和虚拟目录名称不同
#节点用于定义目录的访问权限等
#
#Alias 虚拟目录名称 虚拟目录路径
#
# Options Indexes FollowSymLinks
# AllowOverride All
# Order allow,deny
# Allow from all
#
#下面是具体的示例,/DemoSite是目录别名 "D:/Code/WebSite"是虚拟目录的实际路径
Alias /DemoSite "D:/Code/WebSite"
Options Indexes FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
重启Apache服务后,浏览器输入http://localhost:8080/DemoSite即可正常访问。注意目录路径建议使用正斜杠"/"而非反斜杠"\",因为后者可能被解析为转义符从而引发错误。完整配置节点参考如下:
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://localhost/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "D:/Program Files/Apache2.2/cgi-bin/"
Alias /DemoSite "D:/Code/WebSite"
Options Indexes FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
实现多主机头绑定
多主机头绑定(即在同一端口绑定多个域名,各域名指向不同目录,此概念源自IIS)。打开httpd.conf文件,在末尾追加以下内容以实现多域名解析:
#多主机头配置无需放在特定的节点下面,一般直接在配置文件底部添加即可
#NameVirtualHost addr[:port] 为一个基于域名的虚拟主机指定一个IP地址(和端口)
#声明主机头必须加这条指令,否者主机头配置不会生效
#VirtualHost节点下面ServerName就是要绑定的域名,DocumentRoot表示此域名指向的目录
#本机测试的话请在hosts中进行域名绑定如 127.0.0.1 www.mysite1.com
NameVirtualHost *:8080
ServerName www.mysite1.com
DocumentRoot "D:\Program Files\Apache2.2\htdocs"
ServerName www.mysite2.com
DocumentRoot "D:\Code\MySite"
完成配置并重启Apache后,访问www.mysite1.com:8080会自动重定向至D:\Program Files\Apache2.2\htdocs站点。
访问www.mysite2.com:8080则会自动跳转至D:\Code\MySite站点。通过上述配置,即可在一台服务器上同时运行多个独立站点。