一般架好網站後,一個server上是可以設定多個網站,不過可能就都要listen在不同的port。所以如果我們主機上有主要網站,又有其它網站,例如Blog的話,最常用的建置方式就是用子資料夾(sub-folder)的方式來建置。例如主網站為www.prog-lab.com,而Blog的網址以子資料夾方式架設的話,就會像是www.prog-lab.com/blog。這種方式也沒有什麼不好,只是網址看來就是是附屬的,不像是個獨立的網站。
DNS設定sub-domain
如果你本身是有買域名的話,通常域名管理商都會提供subdomain的方式讓你可以在主要域名的前面再加上其它名稱,建立不同的網址,但都可以指向到同一台server。例如筆者這邊是用godaddy,你可以登入godaddy的網站,並加入一筆CNAME的資料,就可以順利地新增一個sub-domain了。

建立好sub-domain後,在瀏覽器中輸入blog.prog-lab.com就會等同指向你的主網站。
要如何讓你的sub-domain可以再順利地指向到你安裝的wordpress目錄,這部份就要設定你的網站伺服器了。筆者用的是Nginx,所以就說明一下Nginx的設定方式。要提醒的是,如果你是已設定好子資料夾的方式,而要改成sub-domain的話,建議你要先針對你的blog先備份一下。筆者的慘痛經驗就是在將子資料夾轉換成sub-domain的過程中,也不知是哪邊設定錯誤,造成無法再登入wordpress的管理介面。每次要登入管理介面,輸入帳號及密碼,就會再被導回到管理介面的登入畫面。查了其它網站上的解決方案,都無法解決。最後,只好重新架設,並拿回最近的備份資料才順利恢復網站。
Nginx設定sub-domain
nginx要設定sub-domain,比較好的方式是另外再新增一個server的區塊。先找到你的網站設定檔(通常是在/etc/nginx/sites-available/default)。開啟編輯器進行編輯:
# blog server configuration
#
server {
listen 80;
listen [::]:80;
# SSL configuration
#
listen 443 ssl;
listen [::]:443 ssl;
ssl_certificate /etc/nginx/certificate.prog-lab.crt;
ssl_certificate_key /etc/nginx/private.prog-lab.key;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
root /mnt/wwwdata/html/wordpress;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html index.php;
server_name blog.prog-lab.com;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.php?$args;
}
# pass PHP scripts to FastCGI server
#
location ~ \.php$ {
include snippets/fastcgi-php.conf;
# With php-fpm (or other unix sockets):
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
}
}
幾個重點:
- listen 後面記得不要加上default server,因為這個是新增的server區塊,通常你已有其它default server區塊。如這邊也加上default server的話,會發現這份新的設定是無法被使用到的。
- location / 區段記得加上 /index.php?$args; 這樣才能支援非預設的永久連結。
設定好後,可以執行以下指令來重新載入設定檔:
sudo service nginx reload
WordPress設定
wordpress中也要記得到管理後台,將你的wordpress位址及網站位址都改用sub-domain的方式。這樣才能正常運作。