目的:在本地访问时,通过不同域名访问不同的开发目录,本案例将example.com映射到 我的 ~/Desktop目录下
环境:Apache2.4,Ubuntu14.04
工具:vim
1.域名映射
我们得将example.com指向本地ip,以防止域名解析。
修改/etc/hosts文件,
在127.0.0.1 localhost 那一块下方添加一条记录:
127.0.0.1 localhost
127.0.0.1 example.com
2.Apache配置
Ubuntu的Apache2 配置文件结构如下:
# /etc/apache2/
# |-- apache2.conf
# | `-- ports.conf
# |-- mods-enabled
# | |-- *.load
# | `-- *.conf
# |-- conf-enabled
# | `-- *.conf
# `-- sites-enabled
# `-- *.conf
/etc/apache2/apache2.conf 是主配置文件,Apache在启动时会加载这个配置文件,且此配置文件通过 Include 引入其他细分部分的配置文件来使配置信息完整.
ports.conf 一般都会在主配置中引入,它被用来设置监听访问连接的端口,并且该文件可以在任何时候被修改.
mods-enabled/,conf-enabled/ 和 sites-enabled/ 下的文件各自独立地配置 模块,全局配置片段 和 虚拟主机.
#############################################
我们要用到的就是虚拟主机的配置
sites-enabled是链接,指向了sites-available下的conf文件.
而sites-available下才放置了虚拟主机的配置文件.要使此目录下配置文件生效则需要使用 a2ensite 命令,该命令会在sites-enable/ 下创建一个链接指向 sites-available/ 下的一个conf文件.
进入sites-available/,
将默认配置 000-default.conf 拷贝一份,新命名为 example.conf
cp 000-default.conf example.conf
编辑:
#############################################
<VirtualHost *:80>
#域名
ServerName example.com
#管理员邮件
ServerAdmin webmaster@localhost
#网站根目录,设置为我的桌面
DocumentRoot /home/away/Desktop/
<Directory /home/away/Desktop/>
#此处语法注意 Apache2.4 和 2.2不一样
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error-example.com.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
#############################################
使该文件生效,
a2ensite example.conf
service apache2 reload
在桌面创建一个index.html文件
vim /home/away/Desktop/index.html
编辑:
<html>
<h1>Hello,Engineer!</h1>
<html>
保存
浏览器访问http://example.com
大功告成!!
如需使用更多虚拟主机,按以上流程添加新配置即可.