How to install Ghost CMS with Cloudflare worker with domain sub-directory

How to install Ghost CMS on Ubuntu 22 with domain “blog.domain.com” and I want to use cloudflare worker to port it to another official domain “domain.com/blog

安裝 Ghost CMS 在 Ubuntu 22.04

系統準備

  • 更新系統套件:
sudo apt update && sudo apt upgrade -y

安裝必要組件

  1. 安裝 Nginx:
sudo apt install nginx
  1. 安裝 MySQL:
sudo apt install mysql-server
sudo systemctl enable --now mysql
  1. 安裝 Node.js:
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs

設定 Ghost

  1. 安裝 Ghost CLI:
sudo npm install ghost-cli@latest -g
  1. 建立 Ghost 目錄:
sudo mkdir -p /var/www/ghost
sudo chown $USER:$USER /var/www/ghost
sudo chmod 775 /var/www/ghost
  1. 建立 MySQL 資料庫:
sudo mysql -u root -p
CREATE USER 'ghost'@'localhost' IDENTIFIED BY '你的密碼';
CREATE DATABASE ghost_blog;
GRANT ALL PRIVILEGES ON ghost_blog.* TO 'ghost'@'localhost';
FLUSH PRIVILEGES;
EXIT;
  1. 安裝 Ghost:
cd /var/www/ghost
ghost install

安裝過程中需要填寫以下資訊:

  • Blog URL: https://blog.domain.com
  • MySQL hostname: localhost
  • MySQL username: ghost
  • MySQL password: 你的密碼
  • Database name: ghost_blog
  • 設定 Nginx: Yes
  • 設定 SSL: Yes
  • 啟動 Ghost: Yes

設定 Cloudflare Worker 重定向

  1. 在 Cloudflare Dashboard 建立新的 Worker:
const blogDomain = "blog.domain.com";

async function handleRequest(request) {
  const url = new URL(request.url);
  
  // 檢查是否為 domain.com/blog 的請求
  if (url.hostname === "domain.com" && url.pathname.startsWith("/blog")) {
    // 移除 /blog 前綴並重定向到部落格域名
    const newPath = url.pathname.replace("/blog", "") || "/";
    const newUrl = `https://${blogDomain}${newPath}${url.search}${url.hash}`;
    return Response.redirect(newUrl, 301);
  }
  
  return fetch(request);
}

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});
  1. 設定 Worker 路由:
  • 前往 Workers 頁面
  • 點選「Add Route」
  • 路由模式設為:domain.com/blog*
  • 選擇剛才建立的 Worker

DNS 設定

  1. 在 Cloudflare DNS 設定中新增以下記錄:
  • blog.domain.com 新增 A 記錄,指向您的 Ubuntu 伺服器 IP
  • 確保 Proxy 狀態為開啟(橘色雲朵)

完成以上設定後,訪問 domain.com/blog 會自動重定向到 blog.domain.com,而 Ghost CMS 將在該域名下正常運作。

ubuntu how to upgrad node to latest version

使用 NodeSource Repository 更新 Node.js

  1. 清除現有的 npm 快取:
sudo npm cache clean -f
  1. 添加 NodeSource repository:
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
  1. 更新系統並安裝 Node.js:
sudo apt update && sudo apt install nodejs
  1. 更新 npm 到最新版本:
sudo npm install -g npm@latest

使用 n 套件更新 Node.js

  1. 安裝 n 套件:
sudo npm install -g n
  1. 安裝最新穩定版本:
sudo n stable

或安裝最新版本:

sudo n latest

使用 NVM 更新 Node.js

  1. 安裝 NVM:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
  1. 安裝最新的 LTS 版本:
nvm install --lts
  1. 使用新安裝的版本:
nvm use --lts
  1. 更新 npm:
nvm install-latest-npm

完成安裝後,可以使用以下指令確認版本:

node --version
npm --version