1、首先配置host
用管理員權限打開Ubuntu的hosts文件(路徑:/etc/hosts)
sudo vim /etc/hosts //使用管理員權限sudo,用vim編輯器打開hosts文件進行編輯
在host文件的最下面添加 127.0.0.1 域名
127.0.0.1 localhost
127.0.1.1 dev-pc
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
127.0.0.1 www.testxmj.com
#在此處添加,我添加的域名是 www.testxmj.com
2、添加虛擬主機配置
打開 /etc/apache2/sites-available 文件夾,將其中的 000-default.conf 文件(該文件是Apache的例子文件,方便我們用來配置的)複製並重命名粘貼在當前文件夾中。
cd /etc/apache2/sites-available //進入目錄
sudo cp 000-default.conf test.conf //複製並重命名爲test.conf
sudo vim test.conf //編輯test.conf,使用vim,vi,nano編輯器都可以
要編輯的內容如下:
<VirtualHost *:80>
#管理員的郵箱,可不加
#ServerAdmin [email protected]
#服務器的名稱,修改爲 上一步hosts文件添加的域名,最好都加上www
ServerName www.testxmj.com
#服務器的別名,使用別名也可以訪問到,可不加
ServerAlias testxmj.com
#虛擬主機的文件根目錄,項目的目錄,Ubuntu一般都在/var/www/html下
DocumentRoot /var/www/html/estate_macau/public
#打開站點/虛擬主機後,優先顯示的頁面
DirectoryIndex index.php index.html index.htm Welcome.html
#錯誤日誌的存放地址
ErrorLog ${APACHE_LOG_DIR}/error.log
#日誌
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
題外:其中的DirectoryIndex (目錄索引)作用:修改Apache默認起始/索引頁面(localhost默認的打開頁面)
①、Linux下:如上圖
②、win下:需要修改httpd.conf文件
路徑:(在apache的安裝目錄下)…/apache/conf/httpd.conf
<IfModule dir_module>
DirectoryIndex index.php index.html index.htm
</IfModule>
Apache默認索引/打開(瀏覽器輸入localhost打開)的頁面是index.html,想修改成其他文件,需要修改DirectoryIndex後面的文件夾名稱,然後重啓Apache:
Apache會根據DirectoryIndex後面寫的文件名,按從左到右的順序在項目根目錄查找同名文件。比如上圖,如果找到index.php即加載index.php,沒有的話,繼續往右查找是否有index.html文件,有的話加載index.html,沒有的話繼續,以此類推。。。
如果上述設置後仍無法按順序運行首頁,那麼還得修改一下php相關配置文件php.conf(路徑: /etc/httpd/conf.d/php.conf)
找到DirectoryIndex項,修改同上。
3、將改文件連接到 sites-enabled 文集夾
sudo ln -s /etc/apache2/sites-available/test.conf /etc/apache2/sites-enabled/
//將改好的 test.conf 文件鏈接到sites-enabled文件夾
sudo /etc/init.d/apache2 restart //重啓服務即可
4、進行測試
輸入我們添加的域名 www.testxmj.com 或者別名:testxmj.com 進行測試