安裝Nginx
確保你的系統(tǒng)已經(jīng)安裝了Nginx,如果沒(méi)有,請(qǐng)?jiān)L問(wèn)[Nginx官方網(wǎng)站](https://nginx.org/en/download.html)下載并安裝最新版本。
創(chuàng)建虛擬主機(jī)目錄結(jié)構(gòu)
為了配置多個(gè)虛擬主機(jī),你需要?jiǎng)?chuàng)建一個(gè)獨(dú)立的目錄結(jié)構(gòu),如果你想有一個(gè)名為“example.com”的網(wǎng)站,你可以創(chuàng)建以下目錄結(jié)構(gòu):
/example.com/ /etc/nginx/sites-enabled/ example.com.conf /var/www/example.com public_html/ index.php .htaccess
編輯虛擬主機(jī)配置文件
打開(kāi)/etc/nginx/sites-enabled/example.com.conf
文件,編輯如下內(nèi)容:
server { listen 80; server_name example.com www.example.com; root /var/www/example.com/public_html; index index.php index.html index.htm; location / { try_files $uri $uri/ =404; } # PHP處理 include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根據(jù)PHP環(huán)境修改路徑 # SSL設(shè)置(如果需要) # ssl_certificate /path/to/certificate.pem; # ssl_certificate_key /path/to/privatekey.key; }
注意事項(xiàng)
<code>listen 80;</code>
指定了Nginx監(jiān)聽(tīng)HTTP端口。
<code>server_name example.com www.example.com;</code>
設(shè)置了域名名稱。
<code>root /var/www/example.com/public_html;</code>
指定了網(wǎng)站根目錄。
<code>location / { ... }</code>
配置了默認(rèn)頁(yè)面加載規(guī)則。
<code>include snippets/fastcgi-php.conf;</code>
包含了PHP FastCGI相關(guān)的配置。
<code>fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;</code>
指定了FastCGI進(jìn)程的地址。
啟用虛擬主機(jī)
保存配置文件后,重啟Nginx以應(yīng)用更改:
sudo systemctl restart nginx
測(cè)試虛擬主機(jī)
打開(kāi)瀏覽器,訪問(wèn)http://example.com
或http://www.example.com
,檢查是否能夠正常顯示你的網(wǎng)站內(nèi)容。
添加更多的虛擬主機(jī)
要添加更多虛擬主機(jī),只需重復(fù)上述步驟,在不同的目錄下創(chuàng)建新的配置文件即可。
新增虛擬主機(jī) server { listen 80; server_name newdomain.com www.newdomain.com; root /var/www/newdomain.com/public_html; index index.php index.html index.htm; location / { try_files $uri $uri/ =404; } include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; }
通過(guò)以上步驟,你已經(jīng)成功地配置了一個(gè)簡(jiǎn)單的Nginx虛擬主機(jī),這只是一個(gè)基本示例,實(shí)際項(xiàng)目可能需要更復(fù)雜的配置和定制化選項(xiàng),隨著經(jīng)驗(yàn)的積累,你可以進(jìn)一步探索Nginx的強(qiáng)大功能和高級(jí)特性。