IntermediateLesson 16 of 307 min read

GitHub Pages: Publishing a Small Site Safely

Publish a small static site from a repository, find the path problem that breaks links, and fix and test it before going live.

In this lesson you will

  • Explain what GitHub Pages publishes
  • Tell relative links from root-relative links
  • Crawl a site to find broken links
  • Describe the usual publishing steps

About 32 minutes

A website with no server

Nia wants a page for the garden club that anyone can visit, and she does not want to pay for hosting or run a server. GitHub Pages is a feature that publishes the files in a repository as a website. You push ordinary HTML, CSS and image files, and the site serves them as pages. There is no server code to write, so it suits portfolios, project pages and small club sites. Because everything is just files in Git, you already know how to change, review and undo it.

What you need to know first

  • Who can use it. At the time of writing, Pages is available for public repositories on the free plan, and for private ones on paid plans. Plans change, so check GitHub’s current pages.
  • Two kinds of address. A personal site lives in a repository named after your account, with an address of the form username.github.io. A project site usually lives under that address, in a path named for the repository. Check the Pages help for the exact current rules for your kind of site.
  • A publishing source. You tell Pages which branch (and folder) holds the site, using the repository’s settings. Changes can take several minutes to appear after you push.
  • Everything is public. Anything you publish can be read by anyone. Do not put private information in a site.

GitHub itself cannot be reached from the machine that builds these lessons, so the settings are described as patterns. What we can test for real is the part that goes wrong most often: the links.

Build a tiny site

$ mkdir garden-site
$ cd garden-site
$ git init
Initialized empty Git repository in /home/nia/garden-site/.git/
$ printf '%s\n' '<!doctype html><title>Garden notes</title><link rel="stylesheet" href="/style.css"><h1>Garden notes</h1><a href="/about.html">About</a>' > index.html
$ printf '%s\n' '<!doctype html><title>About</title><link rel="stylesheet" href="/style.css"><h1>About</h1><a href="index.html">Home</a>' > about.html
$ printf 'h1 { color: #1F2A44; }\n' > style.css
$ git add .
$ git commit -m "Add a two page site"
[main (root-commit) 123398d] Add a two page site
 3 files changed, 3 insertions(+)
 create mode 100644 about.html
 create mode 100644 index.html
 create mode 100644 style.css
$ git ls-files
about.html
index.html
style.css

Two pages and a style sheet, saved in a commit. Look at the links. The first page points to /style.css and /about.html, with a leading slash. The second page uses a link with no slash. They look almost the same, but they behave differently once the site lives in a folder.

The path problem

A link that starts with a slash means “from the very top of this web address”. If your site lives at the top, that works. But a project site usually lives below the top, in a folder named for the project. Then /style.css points to a place outside your folder, and the file is not found. A link without a leading slash is relative: it is worked out from the page that contains it, so it keeps working wherever the folder is.

The program below proves it. It starts a small web server on your own computer that serves the site under a path named after the project, like a project site would be. Then a crawler visits the first page and follows every link and image address it can find, recording any address that is not found.

import threading, re, urllib.request, urllib.error, os
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
from urllib.parse import urljoin, urlparse

ROOT, PREFIX = "/home/nia/garden-site", "/garden-site/"

class Handler(SimpleHTTPRequestHandler):
    def translate_path(self, path):
        path = urlparse(path).path
        if not path.startswith(PREFIX):
            return "/nonexistent"
        return os.path.join(ROOT, path[len(PREFIX):] or "index.html")
    def log_message(self, *args): pass

def crawl():
    server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    base = "http://127.0.0.1:%d%sindex.html" % (server.server_port, PREFIX)
    todo, seen, broken = [base], set(), []
    while todo:
        url = todo.pop()
        if url in seen: continue
        seen.add(url)
        try:
            body = urllib.request.urlopen(url).read().decode()
        except urllib.error.HTTPError as e:
            broken.append(urlparse(url).path); continue
        if url.endswith(".html"):
            for ref in re.findall(r'(?:href|src)="([^"]+)"', body):
                todo.append(urljoin(url, ref))
    server.shutdown()
    return sorted(seen), broken

seen, broken = crawl()
print("addresses visited:", len(seen))
print("broken:", len(broken))
for b in broken: print("  missing:", b)
addresses visited: 3
broken: 2
  missing: /about.html
  missing: /style.css

The crawler visited 3 addresses and found 2 broken ones: /about.html and /style.css. The page also loaded without its style sheet, so it would have looked plain. Here is the useful part. The same site on your own computer, opened straight from the folder, would have looked fine. Problems like this only show up once the site lives under a path, so test for them before you publish.

Fix, commit, test again

The fix is to remove the leading slash from the links. One command does it for both files, and the change is committed with a clear message. A final listing shows all four links are now relative.

$ sed -i 's#href="/#href="#g' index.html about.html
$ git commit -am "Use relative links"
[main 8d08e0c] Use relative links
 2 files changed, 2 insertions(+), 2 deletions(-)
$ grep -o 'href="[^"]*"' index.html about.html
index.html:href="style.css"
index.html:href="about.html"
about.html:href="style.css"
about.html:href="index.html"
addresses visited: 3
broken: 0

The second crawl found 0 broken addresses. Notice how the whole cycle was ordinary Git: a commit that adds the site, a test, a commit that fixes it, and a test again. The history even records why the links changed.

Publishing it

  1. Push the repository to GitHub, using the commands from lesson 9.
  2. In the repository’s settings, open the Pages section and choose to deploy from a branch.
  3. Pick the branch that holds the site, usually main, and save.
  4. Wait a few minutes, then open the address that GitHub shows you, and click every link.

Those four steps are a pattern, and the screens and wording change over time. When you edit the site later, you commit and push as always, and the published site updates after a short delay. If something goes wrong, git revert from lesson 5 undoes it, and nothing is lost.

Common mistake: links that work only at home

Testing only on your own computer and publishing broken absolute links. Always click through the published site as a visitor, or crawl it with a small program.

An imitation of the path, not GitHub

The site, the club and the project path are made up. The small server here only imitates the way a project site sits under a folder, and GitHub’s own address rules, delays and plan limits can differ, so check its Pages help. Do not put private information on a public site.

Make a one page site with a style sheet and an image. Serve it under a folder name with a small server, crawl it, and fix every broken link before you ever publish.

Practice for this lesson

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does GitHub Pages do?

  1. Runs your private programs
  2. Backs up your computer
  3. Makes commits for you
  4. Publishes the files in a repository as a website

You push HTML and CSS and the site serves them.

Why did the root-relative links break?

  1. A leading slash points to the top of the address, outside the project folder
  2. The files were empty
  3. Git deleted them
  4. The server was off

The crawler could not find /style.css or /about.html under the project path.

What is a relative link?

  1. One that starts with http only
  2. One that is hidden
  3. One worked out from the page that contains it
  4. One that is always broken

It keeps working wherever the site folder sits.

Why should you never put private information on a Pages site?

  1. Git cannot store private files
  2. Pages deletes it
  3. It costs extra
  4. Anything published can be read by anyone

Treat a published site as public.

How do you undo a bad change to a published site?

  1. Delete GitHub
  2. Revert the commit and push
  3. Restart the computer
  4. You cannot undo it

The site is just files in Git, so revert works.

Summary

  • Pages publishes the files in a repository as a website.
  • Anything published is public, and plan rules and delays can change.
  • Links starting with a slash can break when a site lives in a folder; relative links keep working.
  • Test the published path before you announce it, and fix with ordinary commits.

Next lesson

Lesson 17 covers stash, tags and releases.

Questions

Can I use my own domain name?

Pages supports custom domains, and the steps are in GitHub's help pages. They change over time, so follow the current instructions.

Does Pages run PHP or a database?

No. It serves static files. For dynamic features you need other services, or scripts that run in the visitor's browser.

How long until my changes appear?

Usually a few minutes, and the docs say it can take up to about ten. Wait, refresh, and check the settings page for the status.

Progress is saved in this browser.