前置准备

软件/网站名称 链接
XAMPP Download XAMPP
Git Git - Install for Windows
Github GitHub

快速上手

本地

  1. 搜索Apache的httpd.conf文件内DocumentRoot<Directory 并改为:

    DocumentRoot "D:/path/to/your/project"
    <Directory "D:/path/to/your/project">
        Options Indexes FollowSymLinks Includes ExecCGI
        AllowOverride All
        Require all granted
    </Directory>
    
  2. 在GitHub上新建private存储库

  3. 初始化本地存储库

    git init
    
  4. 配置Github信息

    git config --global user.name "username"
    git config --global user.email "your@email.com"
    
  5. 生成SSH密钥

    ssh-keygen -t rsa -b 4096 "your@email.com"
    
    cat ~/.ssh/id_rsa.pub
    

    复制ssh-rsa开头的公钥并导入到Github

  6. 编码

    注意配置好.gitignore,比如.history/.git/config.php等自动生成文件、敏感文件、用户上传的文件最好配置忽略。

    数据库链接文件可区分本地和远程,php示例如下,配置完后,手动复制到服务器:

    <?php
    date_default_timezone_set('Asia/Shanghai');
    
    // ============ 环境检测 ============
    $current_host = $_SERVER['HTTP_HOST'] ?? '';
    $is_local = (
        strpos($current_host, 'localhost') !== false ||
        $current_host === '127.0.0.1' ||
        $current_host === '::1'
    );
    
    // ============ 数据库配置 ============
    if ($is_local) {
        // 本地开发环境(XAMPP)
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "";
        $db_port = 3316; // 本地端口,如需改动可在此修改
    } else {
        // 线上服务器环境
        $servername = "";
        $username = "";
        $password = "";
        $dbname = "";
        $db_port = 3306;
    }
    
    // 创建 PDO 连接
    try {
        $dsn = "mysql:host=$servername;port=$db_port;dbname=$dbname;charset=utf8mb4";
        $pdo = new PDO($dsn, $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        $pdo->exec("SET time_zone = '+08:00'");
        $pdo->exec("SET NAMES utf8mb4");
    } catch (PDOException $e) {
        header('Content-Type: application/json');
        if ($is_local) {
            die(json_encode(['error' => 'PDO 连接失败: ' . $e->getMessage()]));
        } else {
            error_log("PDO 连接失败: " . $e->getMessage());
            die(json_encode(['error' => '数据库连接失败,请稍后重试或联系管理员']));
        }
    }
    
    // 创建 MySQLi 连接
    $conn = new mysqli($servername, $username, $password, $dbname, $db_port);
    $conn->set_charset("utf8mb4");
    $conn->query("SET time_zone = '+08:00'");
    if ($conn->connect_error) {
        header('Content-Type: application/json');
        if ($is_local) {
            die(json_encode(['error' => 'MySQLi 连接失败: ' . $conn->connect_error]));
        } else {
            error_log("MySQLi 连接失败: " . $conn->connect_error);
            die(json_encode(['error' => '数据库连接失败,请稍后重试或联系管理员']));
        }
    }
    ?>
    
  7. 关联远程仓库

    git remote add origin git@github.com:user/repo.git
    
  8. push到远程仓库(首次须指定分支)

    git push -u origin branch-name
    

服务器

  1. 配置Github信息

    git config --global user.name "username"
    git config --global user.email "your@email.com"
    
  2. 生成SSH密钥

    ssh-keygen -t rsa -b 4096 "your@email.com"
    
    cat ~/.ssh/id_rsa.pub
    

    复制ssh-rsa开头的公钥并导入到Github

  3. 在目标目录下执行

    git init
    git pull git@github.com:user/repo.git banch-name
    
  4. 在服务器目标目录下新建depoly.php,内容如下:

    <?php
    $secret = "your_code";
    $target_dir = __DIR__;
    $git_branch = 'main';
    $log_file = __DIR__ . '/deploy.log';
    
    $headers = getallheaders();
    $signature = $headers['X-Hub-Signature-256'] ?? '';
    $payload = file_get_contents('php://input');
    
    if ($secret && $signature) {
        $hash = 'sha256=' . hash_hmac('sha256', $payload, $secret);
        if (!hash_equals($hash, $signature)) {
            http_response_code(403);
            file_put_contents($log_file, date('Y-m-d H:i:s') . " - 签名验证失败\n", FILE_APPEND);
            die('签名验证失败');
        }
    }
    
    $data = json_decode($payload, true);
    
    if (isset($data['ref']) && $data['ref'] === "refs/heads/$git_branch") {
        $command = "cd $target_dir && git pull origin $git_branch 2>&1";
        $output = shell_exec($command);
    
        $log_message = date('Y-m-d H:i:s') . " - 部署触发\n输出:\n" . $output . "\n---\n";
        file_put_contents($log_file, $log_message, FILE_APPEND);
    
        echo "部署成功";
    } else {
        echo "非目标分支,忽略";
    }
    ?>
    
  5. 项目Webhooks配置如下:

    类别 内容
    Payload URL your.domain/deploy.php
    Content type application/json
    SSL verification Enable SSL verification
    Which events would you like to trigger this webhook? Just the push event.
    Active yes

至此,部署完毕!

故障排查

git push 时提示权限拒绝

原因:SSH 密钥未正确配置 解决

# 测试 SSH 连接
ssh -T git@github.com
# 如果失败,重新添加公钥到 GitHub

部署后网站没更新

原因:Webhook 未触发或 git pull 失败 解决

# 1. 查看部署日志
cat ~/domains/your.domain/public_html/deploy.log

# 2. 手动拉取测试
cd ~/domains/your.domain/public_html
git pull origin main

# 3. 检查 GitHub Webhooks 页面是否有红色 ×

安全提醒

  • 永远不要提交包含密码的文件到 GitHub
  • 线上数据库密码建议用环境变量或独立配置文件(在 .gitignore 中排除)