| | |

GitHub Pages 11 ๐Ÿ“„ PR Previews & Multi-Version Sites โ€” Building subfolder-based preview deployments and versioned docs workflows

โฑ๏ธ Estimated read: 13 min | |

GitHub Pages is a remarkably efficient tool for hosting static content, but its native design is centered around a single site per repository. While competitors like Vercel or Netlify offer built-in “Preview Deployments” for every Pull Request, GitHub Pages requires a more architectural approach to achieve similar functionality. By leveraging GitHub Actions and a strategic subfolder structure on the deployment branch, developers can transform a single GitHub Pages site into a multi-environment hosting platform.

This chapter explores the methodologies used to host multiple versions of documentation and dynamic PR previews on a single domain. We will examine how to manage the gh-pages branch as a collection of directories rather than a single root-level build. This allows for workflows where example.com/v1.0/, example.com/v2.0/, and example.com/pr-42/ can coexist seamlessly, each serving a unique version of the project.

We will focus on the automation required to make this workflow sustainable. Manually managing folders in a deployment branch is error-prone and tedious. Instead, we will build a robust GitHub Actions pipeline that identifies the context of a pushโ€”whether it is a release tag, a merge to the main branch, or an incoming pull requestโ€”and directs the build output to the appropriate subdirectory while maintaining a global navigation system.

The sections follow walk through the architecture of subfolder-based routing, the logic for automated versioning via Git tags, and the cleanup strategies required to prevent the deployment branch from bloating with abandoned PR previews.

Key point: GitHub Pages does not natively support preview environments, so we must simulate them by building projects into named subdirectories (e.g., /pr-5/) on the deployment branch and using GitHub Actions to manage the lifecycle of these folders.


Why exists

The single-site limitation. GitHub Pages was originally designed to serve one site per repository, usually from the root of the gh-pages branch or a /docs folder. This makes it difficult for teams to verify changes in a live environment before merging them into the production branch.

The documentation lifecycle problem. Software projects often need to maintain documentation for multiple versions of their product simultaneously. Users on an older LTS version of a library need the v1.x docs, while early adopters need v2.x. A standard GitHub Pages setup overwrites the site every time a new version is released.

The feedback loop bottleneck. Without PR previews, reviewers must pull code locally and run a dev server to see visual changes. This creates a significant friction point in the code review process, especially for UI-heavy projects or complex documentation sites where CSS changes might have unintended side effects.

The trade-off of “One Source of Truth.” Moving to a multi-version site requires a shift in how we view the deployment branch. It is no longer a mirror of the source code’s current state; it becomes a historical archive of builds. This adds complexity to the CI/CD pipeline but provides immense value in terms of historical reference and QA.

The environment parity challenge. By using subfolders, we can ensure that the “staging” (PR) environment uses the same hosting infrastructure, headers, and routing logic as the production site. This minimizes “works on my machine” bugs that occur when local dev servers behave differently than the final production host.

The risk of branch bloat. If every PR creates a folder that is never deleted, the gh-pages branch will eventually grow to gigabytes in size, slowing down clones and potentially hitting GitHub’s repository size limits. A versioning strategy must exist to purge old data.


a. Architecture of Subfolder-Based Routing

To host multiple versions or previews, we must treat the gh-pages branch as a file system. Instead of placing index.html at the root, we place it within a folder named after the version or PR number. The primary challenge here is path resolution. Most static site generators (SSG) assume they are served from the root. When moved to /pr-123/, links to /css/style.css will break because they look at the domain root, not the subfolder.

To fix this, the build process must be “base-path aware.” We pass a variable to the SSG during build time to prefix all internal links with the correct subfolder path.

# Example snippet for a build step that handles base paths
- name: Build with Base Path
  run: |
    # If this is a PR, set the path to /pr-<number>
    # If it is a tag, set the path to /v<version>
    # Otherwise, it is the root /
    export BASE_PATH="/${{ steps.vars.outputs.dest_folder }}"
    npm run build -- --base-url=$BASE_PATH

The directory structure on the gh-pages branch should look like this:

. (root)
โ”œโ”€โ”€ index.html         # Redirects to /latest/ or /v1/
โ”œโ”€โ”€ latest/            # The current production version
โ”œโ”€โ”€ v1.0/              # Legacy version
โ”œโ”€โ”€ v2.0/              # Current version (symlinked to latest)
โ””โ”€โ”€ pr-42/             # Preview for Pull Request #42

In this architecture, the root index.html often contains a simple JavaScript or Meta-tag redirect. This ensures that users landing on the base URL are sent to the most recent stable version of the content, while specific versions remain accessible via direct links.

The deployment action must be configured to “deploy to a subfolder” without deleting existing content. Most popular deployment actions (like JamesIves/github-pages-deploy-action) have a folder parameter for the source and a target-folder parameter for the destination on the remote branch. By setting clean: false, we prevent the action from wiping out other versions when a new PR preview is uploaded.


b. Automated Versioning and “Latest” Aliasing

A robust versioning workflow relies on Git tags. When a new tag (e.g., v1.2.0) is pushed, the CI should trigger a build and place the output in a folder named v1.2.0. However, users shouldn’t have to update their bookmarks for every minor release. We solve this by maintaining a latest/ folder or a symbolic link.

Since GitHub Pages is a static host, it doesn’t support traditional server-side symlinks. Instead, we “simulate” a symlink by copying the contents of the latest version into the latest/ folder during every release build.

# Script logic inside GitHub Actions to handle the "latest" alias
if [[ $GITHUB_REF == refs/tags/* ]]; then
  TAG_NAME=${GITHUB_REF#refs/tags/}
  # Deploy to the specific version folder
  deploy_to_folder "versions/$TAG_NAME"
  # Also update the 'latest' folder
  deploy_to_folder "latest"
fi

Another critical component is the versions.json file. This file lives at the root of the site and contains a list of all available versions. The frontend of your documentation site can fetch this JSON to populate a version-switcher dropdown menu.

[
  { "version": "v1.0.0", "url": "/v1.0.0/" },
  { "version": "v1.1.0", "url": "/v1.1.0/" },
  { "version": "v2.0.0 (Latest)", "url": "/latest/" }
]

When a new version is deployed, the GitHub Action should also update this JSON file. This creates a fully dynamic documentation portal where new versions appear in the UI automatically as soon as the CI finishes. This logic prevents the need for manual commits to update navigation bars across dozens of static HTML files.


c. PR Preview Lifecycle and Automated Cleanup

PR previews are ephemeral. They should exist only as long as the Pull Request is open. To implement this, we need two separate GitHub Action workflows. The first workflow triggers on pull_request (specifically opened and synchronize events) to build and deploy the preview.

The second workflow is the “Cleanup” routine. It triggers on pull_request with the closed action. When a developer merges or closes a PR, this action checks out the gh-pages branch, deletes the folder corresponding to that PR number, and pushes the change back.

# Logic for the cleanup action
- name: Delete PR Folder
  run: |
    git checkout gh-pages
    rm -rf pr-${{ github.event.number }}
    git add .
    git commit -m "Remove preview for PR ${{ github.event.number }}"
    git push origin gh-pages

Without this cleanup step, your deployment branch will eventually contain hundreds of dead folders. This not only consumes storage but makes the branch history difficult to audit.

To provide a high-quality developer experience, the PR preview workflow should also use the marocchino/sticky-pull-request-comment action. This automatically posts a comment on the PR with a link to the live preview once the deployment is finished. This allows reviewers to click a single link from the GitHub interface to see the changes, mimicking the functionality of premium hosting providers.

### ๐Ÿš€ PR Preview is ready!

- **Preview URL:** [https://user.github.io/repo/pr-42/](https://user.github.io/repo/pr-42/)
- **Last Updated:** 2023-10-27 14:00 UTC

Complete Example Session

# ============================================
# PART 1: WORKFLOW TRIGGER CONFIGURATION
# ============================================
name: Multi-Version Deploy
on:
  push:
    branches: [ main ]
    tags: [ 'v*' ]
  pull_request:
    types: [ opened, synchronize, closed ]

# ============================================
# PART 2: ENVIRONMENT VARIABLES AND PATHS
# ============================================
jobs:
  deploy:
    if: github.event.action != 'closed'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

# ============================================
# PART 3: CALCULATING THE TARGET FOLDER
# ============================================
      - name: Set Destination Folder
        id: set_folder
        run: |
          if [[ "${{ github.event_name }}" == "pull_request" ]]; then
            echo "dest=pr-${{ github.event.number }}" >> $GITHUB_OUTPUT
          elif [[ "${{ github.ref }}" == refs/tags/* ]]; then
            echo "dest=${{ github.ref_name }}" >> $GITHUB_OUTPUT
          else
            echo "dest=latest" >> $GITHUB_OUTPUT
          fi
          # This step determines if we are in /pr-X, /vX.X, or /latest

# ============================================
# PART 4: BUILDING THE STATIC SITE
# ============================================
      - name: Build Application
        run: |
          npm install
          # Pass the calculated folder as the base path for assets
          export BASE_URL="/${{ github.event.repository.name }}/${{ steps.set_folder.outputs.dest }}/"
          npm run build -- --base=$BASE_URL

# ============================================
# PART 5: DEPLOYING TO SUBFOLDER
# ============================================
      - name: Deploy to GitHub Pages
        uses: JamesIves/github-pages-deploy-action@v4
        with:
          branch: gh-pages
          folder: dist # The local build output
          target-folder: ${{ steps.set_folder.outputs.dest }}
          clean: false # IMPORTANT: Do not delete existing folders

# ============================================
# PART 6: PR COMMENTING (PREVIEW LINK)
# ============================================
      - name: Comment Preview Link
        if: github.event_name == 'pull_request'
        uses: marocchino/sticky-pull-request-comment@v2
        with:
          message: |
            PR Preview: https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}/${{ steps.set_folder.outputs.dest }}/

# ============================================
# PART 7: CLEANUP JOB SETUP
# ============================================
  cleanup:
    if: github.event.action == 'closed'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout gh-pages
        uses: actions/checkout@v4
        with:
          ref: gh-pages

# ============================================
# PART 8: REMOVING PR DIRECTORY
# ============================================
      - name: Delete PR folder
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          rm -rf pr-${{ github.event.number }}
          # Only commit if changes exist
          git add .
          git diff-index --quiet HEAD || git commit -m "Cleanup pr-${{ github.event.number }}"

# ============================================
# PART 9: PUSHING CLEANUP CHANGES
# ============================================
      - name: Push Changes
        run: git push origin gh-pages

# ============================================
# PART 10: UPDATE VERSION INDEX (OPTIONAL)
# ============================================
# (Hypothetical step to rebuild a global index.html for navigation)

The example above demonstrates a complete lifecycle: calculating the destination folder, building with a custom base path, deploying without wiping other folders, commenting on the PR, and cleaning up after a merge.


Quick Reference

Target Folder Logic

ContextRecommended FolderExample Path
Pull Requestpr-<number>/pr-42/
Release Tagv<semver>/v1.2.0/
Main Branchlatest or root/latest/
Feature Branchbranch-<name>/branch-dev/

Path Resolution Variables

ToolVariable/FlagDescription
VitebaseSets the base path for assets/scripts
WebpackpublicPathControls the URL prefix for generated files
DocusaurusbaseUrlRequired for multi-version subfolders
JekyllbaseurlSpecified in _config.yml

Deployment Action Settings (JamesIves)

ParameterValueReason
target-folderVariableIsolates the build into its own directory
cleanfalsePrevents deleting other versions/previews
branchgh-pagesThe standard branch for hosting
folderdistThe folder containing the built files

Best Practices

โœ… Do This:

# Use environment variables to handle base URLs dynamically
- run: npm run build -- --base=/${{ steps.vars.outputs.folder }}/  // โœ…

# Use 'clean: false' to keep multiple versions alive
with: { clean: false, target-folder: 'v1.0' }                      // โœ…

# Implement a cleanup job for Pull Requests
if: github.event.action == 'closed'                                // โœ…

# Use a specific version for the deployment action to ensure stability
uses: JamesIves/github-pages-deploy-action@v4.4.3                 // โœ…

โŒ Don’t Do This:

# Don't hardcode the base URL in your application source code
const url = "https://mysite.com/dist/";                            // โŒ

# Don't deploy to the root of gh-pages if using multi-versions
with: { target-folder: '.' }                                       // โŒ

# Don't forget to configure Git credentials in cleanup scripts
git commit -m "cleanup"                                            // โŒ

# Don't run the build for 'closed' PR events
jobs: { build: { if: github.event.action != 'closed' } }          // โŒ

Common Pitfalls

PitfallWhy It HappensFix
404 on AssetsApp expects root path but is in subfolderConfigure base_url in the SSG build step
Prevents New Deploygh-pages branch is locked or protectedAllow GitHub Actions to bypass branch protection
Bloated Repo SizeOld PR previews are never deletedAdd a closed PR trigger to delete folders
Version Switcher BrokenJSON index not updated on new tagsScript the versions.json update in the CI
Deployment ConflictsMultiple CI runs pushing to same branchUse concurrency group in GitHub Actions

Real-World Examples

1. Vite Base Path

// vite.config.js
export default {
  base: process.env.BASE_URL || '/', // Dynamic base path
};

2. Docusaurus Config

// docusaurus.config.js
module.exports = {
  baseUrl: process.env.DOCS_BASE_URL || '/',
};

3. Root Redirect (index.html)

<meta http-equiv="refresh" content="0; url=/latest/">
<script>window.location.href = "/latest/"</script>

4. Sticky PR Comment

uses: marocchino/sticky-pull-request-comment@v2
with:
  header: preview
  message: "Preview: [Click here](${{ env.URL }})"

5. Deleting a directory via CI

git rm -rf pr-55 && git commit -m "Remove PR 55"

6. Version JSON Update

# Append new version to array
jq '. += [{"v": "1.1"}]' versions.json > tmp.json && mv tmp.json versions.json

7. GitHub Action Concurrency

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true # Prevent overlapping pushes

8. MkDocs Base URL

mkdocs build --site-dir dist/v1.0 --use-directory-urls

9. Custom Domain Check

# Ensure CNAME file is preserved during subfolder deploy
cp CNAME dist/ || true

10. Fetching PR Number

PR_NUM=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH")

Visual

Multi-Version Directory Tree

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ GH-PAGES BRANCH STRUCTURE                                 โ”‚
โ”‚                                                           โ”‚
โ”‚  / (root)                                                 โ”‚
โ”‚  โ”œโ”€โ”€ index.html  โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Redirects to /latest/          โ”‚
โ”‚  โ”œโ”€โ”€ versions.json โ”€โ”€โ”€โ”€โ”€โ”€โ–บ UI for Version Switcher        โ”‚
โ”‚  โ”‚                                                        โ”‚
โ”‚  โ”œโ”€โ”€ latest/     โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Synced with most recent tag    โ”‚
โ”‚  โ”‚   โ”œโ”€โ”€ index.html                                       โ”‚
โ”‚  โ”‚   โ””โ”€โ”€ assets/                                          โ”‚
โ”‚  โ”‚                                                        โ”‚
โ”‚  โ”œโ”€โ”€ v1.0.0/     โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Frozen legacy version          โ”‚
โ”‚  โ”œโ”€โ”€ v2.0.0/     โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Static release build           โ”‚
โ”‚  โ”‚                                                        โ”‚
โ”‚  โ”œโ”€โ”€ pr-12/      โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Temporary preview              โ”‚
โ”‚  โ””โ”€โ”€ pr-15/      โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Deleted after merge            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Deployment Pipeline Logic

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ TRIGGER EVENT            DESTINATION LOGIC                โ”‚
โ”‚                                                           โ”‚
โ”‚ [Push to Main] โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Build โ”€โ”€โ”€โ–บ Deploy to /latest/    โ”‚
โ”‚                                                           โ”‚
โ”‚ [Push Tag v1.2] โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Build โ”€โ”€โ”€โ–บ Deploy to /v1.2/      โ”‚
โ”‚                                                           โ”‚
โ”‚ [Open PR #45] โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Build โ”€โ”€โ”€โ–บ Deploy to /pr-45/     โ”‚
โ”‚                                                           โ”‚
โ”‚ [Close PR #45] โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ Action โ”€โ”€โ–บ 'rm -rf pr-45'        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Asset Path Resolution

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ URL: mysite.com/pr-12/index.html                          โ”‚
โ”‚                                                           โ”‚
โ”‚ โŒ WRONG: <script src="/app.js">                          โ”‚
โ”‚    (Looks for mysite.com/app.js)                          โ”‚
โ”‚                                                           โ”‚
โ”‚ โœ… RIGHT: <script src="/pr-12/app.js">                    โ”‚
โ”‚    (Injected via BASE_URL env var during build)           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
StrategySubfolder-based isolation
ToolingGitHub Actions + Deployment Action
Preview Triggerpull_request (opened, synchronize)
Cleanup Triggerpull_request (closed)
Asset FixBase-URL build configuration
Release LogicTag-based folder naming
User EntryRoot level index.html redirect
DiscoverabilityCentral versions.json file

Key takeaways:

  • GitHub Pages supports subfolders. We can treat the deployment branch as a directory-based hosting service by specifying target-folder in our CI/CD configuration.
  • Base paths are the biggest hurdle. Always ensure your static site generator is configured with a dynamic base URL that matches the destination subfolder to prevent broken assets.
  • Cleanup is mandatory. Automated removal of PR preview folders on the closed event is essential for maintaining a clean and performant repository.
  • The “Latest” alias simplifies UX. Redirecting the root domain to a /latest/ folder allows you to update documentation versions without breaking external links.
  • Sticky comments improve workflow. Posting the preview URL directly into the Pull Request conversation significantly speeds up the review and approval process.

Remember: GitHub Pages is “dumb” hostingโ€”it doesn’t know about branches or versions. All the intelligence must reside in your GitHub Actions workflow. By carefully managing how files are organized on the gh-pages branch, you can create a professional-grade documentation and preview system that rivals expensive proprietary hosting platforms.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!