在PHP中,虛擬主機(jī)是通過(guò)配置Apache或其他Web服務(wù)器來(lái)實(shí)現(xiàn)的,以下是使用Apache和PHP來(lái)設(shè)置虛擬主機(jī)的基本步驟:
1、安裝Apache和PHP
你需要在你的服務(wù)器上安裝Apache和PHP,你可以使用包管理器(如aptget或yum)來(lái)安裝它們。
2、創(chuàng)建虛擬主機(jī)配置文件
你需要為你的虛擬主機(jī)創(chuàng)建一個(gè)配置文件,這個(gè)文件通常位于/etc/apache2/sitesavailable/目錄下,在這個(gè)文件中,你可以定義虛擬主機(jī)的各種設(shè)置,如文檔根目錄、錯(cuò)誤日志等。
3、啟用虛擬主機(jī)
創(chuàng)建完配置文件后,你需要啟用它,這可以通過(guò)運(yùn)行a2ensite命令來(lái)完成。
4、重啟Apache
你需要重啟Apache以使更改生效,這可以通過(guò)運(yùn)行service apache2 restart命令來(lái)完成。
以下是一個(gè)簡(jiǎn)單的虛擬主機(jī)配置文件的例子:
<VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/mywebsite ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
在這個(gè)例子中,我們定義了一個(gè)監(jiān)聽(tīng)80端口的虛擬主機(jī),服務(wù)器管理員的電子郵件地址是webmaster@localhost,文檔根目錄是/var/www/mywebsite,錯(cuò)誤日志和訪問(wèn)日志分別存儲(chǔ)在/var/log/apache2/error.log和/var/log/apache2/access.log中。
下面是一個(gè)簡(jiǎn)單的介紹,展示了如何在不同的操作系統(tǒng)和Web服務(wù)器上開(kāi)啟php虛擬主機(jī)的配置步驟:
/etc/httpd/conf/httpd.conf
或/etc/apache2/apache2.conf
C:Program Files (x86)Apache GroupApacheconfhttpd.conf
或在虛擬主機(jī)配置文件中/etc/nginx/nginx.conf
或在虛擬主機(jī)的配置文件中,通常位于/etc/nginx/sitesavailable/
下面是針對(duì)不同服務(wù)器的配置示例:
Apache
Linux
打開(kāi)httpd.conf 或 apache2.conf <VirtualHost *:80> ServerAdmin webmaster@dummyhost.example.com DocumentRoot /var/www/html ServerName dummyhost.example.com ServerAlias www.dummyhost.example.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # 開(kāi)啟PHP支持 AddType application/xhttpdphp .php PHPIniDir "/etc/php/7.x/apache2" # 根據(jù)你的PHP版本和配置更改路徑 </VirtualHost>
Windows
打開(kāi)httpd.conf <VirtualHost *:80> ServerAdmin webmaster@dummyhost.example.com DocumentRoot "C:wwwdummyhost" ServerName dummyhost.example.com ServerAlias www.dummyhost.example.com ErrorLog "logs/dummyhosterror.log" CustomLog "logs/dummyhostaccess.log" combined # 開(kāi)啟PHP支持 AddType application/xhttpdphp .php PHPIniDir "C:php" # 根據(jù)你的PHP安裝路徑更改 </VirtualHost>
Nginx
Linux
打開(kāi)虛擬主機(jī)配置文件 server { listen 80; server_name dummyhost.example.com www.dummyhost.example.com; root /var/www/html; index index.php index.html index.htm; location / { try_files $uri $uri/ =404; } # PHP 處理 location ~ .php$ { include snippets/fastcgiphp.conf; fastcgi_pass unix:/var/run/php/php7.xfpm.sock; # 根據(jù)你的PHPFPM版本和配置更改 } }
請(qǐng)根據(jù)你的實(shí)際環(huán)境替換示例中的路徑、文件名和服務(wù)器配置。
記得在修改配置文件后重啟Web服務(wù)器使更改生效。
Apache:service httpd restart
或systemctl restart apache2
Nginx:service nginx restart
或systemctl restart nginx