Short answer: GitHub branch protection stops risky changes to important branches such as main. The minimum safe setup blocks force pushes and branch deletion; teams add required pull requests and passing CI checks. Use rulesets rather than classic rules for new setups, because they layer, support bypass lists and can be applied to many repositories with the GitHub CLI.

Key takeaways

  • Branch protection guards against your own mistakes; outsiders can never push to your repository without collaborator access.
  • Start with two rules that never break a workflow: block deletion and block force pushes.
  • Add pull request reviews and required status checks only when your workflow uses branches and CI.
  • Rulesets replace classic rules for most new setups: they layer, target tags too and support bypass actors.
  • On a free personal account, protection works on public repositories; private repositories need a paid plan.
github branch protection with rulesets: block deletion and force push, require pull requests and CI, apply to every repository
GitHub branch protection with rulesets: block deletion and force pushes, require pull requests and CI, and roll out to every repository.

GitHub shows a banner on new repositories: “Your main branch isn’t protected.” Many developers dismiss it, and many beginners worry it means strangers can change their code. Neither reaction is right. The banner is a reminder that one bad command, such as a force push or an accidental branch deletion, can rewrite or remove your history, and that a few rules prevent it.

I maintain more than 170 public repositories, most created by scripts. This guide explains what branch protection actually does, the difference between classic rules and rulesets, and how I apply a safe baseline to every repository with the GitHub CLI without breaking automated workflows.

What is GitHub branch protection?

GitHub branch protection is a set of rules attached to a branch that controls how it can change. Typical rules block force pushes and deletion, require changes to arrive through pull requests with reviews, and require status checks such as tests to pass before merging. The goal is to protect history and keep the main branch working.

Protected branch: a branch with at least one protection rule or ruleset applied to it.

Force push: a push that rewrites branch history, for example after a rebase. On a shared branch it can delete other people’s commits.

Status check: a result reported by CI, such as a GitHub Actions job named “test”, that can be required before merging.

Can other people push to my repository without protection?

No. Only you and collaborators you add can push to your repository, whether or not a branch is protected. Everyone else must fork the repository and open a pull request, and nothing changes until you merge it. Branch protection mainly protects the main branch from mistakes by people who already have write access.

That includes you and your automation. A script that runs git push --force on the wrong branch, a mistaken git push origin --delete main, or a merge of a pull request with failing tests are the real risks.

Branch protection rules vs rulesets: what is the difference?

Classic branch protection rules apply one set of settings per branch pattern, and only one rule applies to a branch. Rulesets are the newer system: multiple rulesets can apply at once and their rules combine, they can target tags as well as branches, they support bypass lists, and organizations can manage them centrally.

Feature Classic branch protection Rulesets
Rules per branch One matching rule applies Several rulesets layer; the strictest wins
Targets Branches Branches and tags (and pushes on some plans)
Who can bypass Admins (optional enforcement) Bypass list of roles, teams and apps
Visibility Admins only Anyone with read access can see active rules
Organization-wide No Yes, with repository targeting
Status Still supported Recommended for new setups

Both systems can coexist. When a branch is covered by a classic rule and a ruleset, GitHub enforces the combination.

Is branch protection free for private repositories?

On GitHub Free, protected branches and rulesets work on public repositories. For private repositories on a personal account you need GitHub Pro, and for organization-owned private repositories GitHub Team or Enterprise. Check your plan before expecting rules to apply to private code.

From my own work: When I checked my own account, every one of my repositories had an unprotected default branch, including the private ones where the free plan cannot enforce rules anyway. For the public ones I chose only the two rules that never get in the way of scripts: no deletion and no force pushes.

Which rules should you turn on?

Turn on rules that match how you work. Blocking deletion and force pushes is safe for almost everyone. Requiring pull requests, reviews and status checks is excellent for teams but will reject direct pushes from solo developers and automation unless you add a bypass.

Rule What it does Who should use it
Restrict deletions Stops the branch being deleted Everyone
Block force pushes Stops history rewrites Everyone
Require linear history Allows only squash or rebase merges Teams that want a clean log
Require a pull request No direct pushes; changes arrive via PR Teams; solo devs using branches
Required approvals N reviews before merge Teams with reviewers
Required status checks CI must pass before merge Any repository with CI
Require signed commits Only verified commits Security-sensitive projects

Step 1: the minimal ruleset for any repository

This ruleset protects the default branch, whatever it is called, from deletion and force pushes. It never blocks a normal push, so it is safe for solo developers, scripts and bots. Save it as ruleset.json.

{
  "name": "Protect default branch",
  "target": "branch",
  "enforcement": "active",
  "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
  "rules": [
    { "type": "deletion" },
    { "type": "non_fast_forward" }
  ]
}

~DEFAULT_BRANCH is a special value that follows the repository’s default branch, so the same file works for repositories using main or master.

Step 2: apply it with the GitHub CLI

The GitHub CLI can call the REST API directly. Authenticate once with gh auth login, then create the ruleset and check which rules apply to a branch.

# Create the ruleset on one repository
gh api repos/OWNER/REPO/rulesets -X POST --input ruleset.json

# List rulesets and see what applies to a branch
gh api repos/OWNER/REPO/rulesets
gh api repos/OWNER/REPO/rules/branches/main

You can also create rulesets in the web interface under Settings, Rules, Rulesets, which is useful to explore options before scripting them.

Step 3: test that the rules work

Always test new protection. Try a force push and a branch deletion on a test repository; both should be rejected with a repository rule violation message. If they succeed, check the ruleset’s enforcement status and target.

# Should be rejected after the ruleset is active
git push --force origin main
# remote: error: GH013: Repository rule violations found for refs/heads/main.
# remote: - Cannot force-push to this branch

git push origin --delete main
# remote: - Cannot delete this branch

Step 4: a stricter ruleset for teams with CI

Teams usually want every change reviewed and tested. This ruleset requires a pull request with one approval, resolved review threads, a linear history and a passing “test” status check from CI. A bypass entry lets repository admins merge through pull requests in an emergency.

{
  "name": "Main: PR + green CI",
  "target": "branch",
  "enforcement": "active",
  "conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
  "bypass_actors": [
    { "actor_id": 5, "actor_type": "RepositoryRole", "bypass_mode": "pull_request" }
  ],
  "rules": [
    { "type": "deletion" },
    { "type": "non_fast_forward" },
    { "type": "required_linear_history" },
    { "type": "pull_request", "parameters": {
        "required_approving_review_count": 1,
        "dismiss_stale_reviews_on_push": true,
        "require_code_owner_review": false,
        "require_last_push_approval": false,
        "required_review_thread_resolution": true } },
    { "type": "required_status_checks", "parameters": {
        "strict_required_status_checks_policy": true,
        "required_status_checks": [ { "context": "test" } ] } }
  ]
}

The context must match the name of the check as GitHub reports it, which for GitHub Actions is usually the job name. Run the workflow once before requiring it, otherwise pull requests wait for a check that never reports. My guide on GitHub Actions security hardening covers safe CI workflows, and deploying WordPress with GitHub Actions shows a full pipeline.

Step 5: apply branch protection to every repository

For an organization, create an organization ruleset and target all repositories. For a personal account, loop over your repositories with the CLI. The script below applies the minimal ruleset to every public, non-archived source repository and skips those that already have it.

#!/usr/bin/env bash
# Apply the minimal ruleset to every public, non-archived, non-fork repo you own
set -euo pipefail
OWNER=your-username
gh repo list "$OWNER" --limit 500 --visibility public --source --no-archived 
  --json name -q '.[].name' | while read -r repo; do
  if gh api "repos/$OWNER/$repo/rulesets" -q '.[].name' | grep -qx "Protect default branch"; then
    echo "skip  $repo (already has it)"; continue
  fi
  gh api "repos/$OWNER/$repo/rulesets" -X POST --input ruleset.json >/dev/null 
    && echo "ok    $repo" || echo "FAIL  $repo"
  sleep 1   # stay well inside API rate limits
done

Run it first on two or three repositories, then on all. The pause between calls keeps you well within API rate limits. Private repositories on a free plan will return an error, which the script reports and skips.

How to set classic branch protection with the API

If you prefer classic rules, for example to match an existing setup, the protection endpoint applies them to one branch. The JSON fields mirror the settings page.

# Classic branch protection via the REST API (one branch, one repo)
gh api repos/OWNER/REPO/branches/main/protection -X PUT --input - <<'JSON'
{
  "required_status_checks": { "strict": true, "contexts": ["test"] },
  "enforce_admins": false,
  "required_pull_request_reviews": { "required_approving_review_count": 1 },
  "restrictions": null,
  "allow_force_pushes": false,
  "allow_deletions": false
}
JSON

How do you protect tags and release branches?

Releases often depend on tags such as v1.2.0 and on release branches. Rulesets can target tags as well as branches, so you can stop anyone from deleting or moving a published release tag. Use a pattern such as v* for tags and release/* for branches, and block deletion and updates for both.

  • Tag rulesets: set the target to tag and include refs/tags/v*; block deletion and non-fast-forward updates so published versions cannot be rewritten.
  • Release branches: include refs/heads/release/* and require pull requests and passing checks, like main.
  • Package registries: immutable tags keep downloads reproducible for users of your library or action.

Should you use CODEOWNERS with branch protection?

A CODEOWNERS file maps paths to people or teams who must review changes to them. Combined with a ruleset that requires code owner review, it guarantees that the right person approves changes to sensitive areas such as deployment workflows, infrastructure code or billing logic. For solo projects it adds little; for teams it is one of the most effective controls.

Put the file in .github/CODEOWNERS, start with broad rules such as the whole .github/workflows/ folder, and keep the list short so reviews do not become a bottleneck.

How bypass lists and emergency fixes work

Rulesets can list bypass actors such as repository roles, teams, GitHub Apps or deploy keys. Choose “always” to let them push directly, or “pull request” to let them merge a pull request that does not meet every rule. Keep the list short and review it, because every bypass weakens the protection.

  • Add your release or deployment bot only if it truly needs to push to main.
  • Prefer temporary changes over permanent bypasses for one-off emergencies.
  • Use evaluate mode, where your plan offers it, to see what a ruleset would block before enforcing it.

Common branch protection mistakes

  • Requiring a check that never runs: pull requests wait forever; run CI once first and match the exact name.
  • Breaking automation: scripts that push to main fail after enabling pull request rules.
  • Only protecting main: release branches and tags may need protection too.
  • Too many bypasses: admins who always bypass make the rules decorative.
  • Assuming private repositories are protected on a plan that does not support it.

What if history was already force-pushed?

If someone force-pushed over main, look for the old commit in a local clone with git reflog, in the pull request timeline, or in the repository’s activity view, then restore it to a branch and push. Act quickly while clones still have the old commits. Then add the rules so it cannot happen again. When you need to find which commit introduced a bug afterwards, git bisect is the fastest tool.

GitHub branch protection checklist

  • Default branch blocks deletion and force pushes.
  • Pull request and review rules match your team size.
  • Required checks exist and use the exact job names.
  • Bypass list is minimal and reviewed.
  • Release branches and tags considered.
  • Rules tested with a force push and delete attempt.
  • Plan supports protection for private repositories.
  • Rollout script or organization ruleset covers all repositories.

Want this done on your own server or site?

I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.

FAQ

What is GitHub branch protection?

Branch protection is a set of rules on a branch, such as main, that stops risky changes. Common rules block force pushes and deletion, require pull requests and reviews before merging, and require status checks such as CI tests to pass. They protect history and code quality.

What is the difference between branch protection rules and rulesets?

Classic branch protection rules apply one set of settings to branches matching a pattern, and only one rule applies per branch. Rulesets are newer: several can apply at once and they layer, they can target branches and tags, they support bypass lists and evaluate mode, and they can be managed at organization level.

Is branch protection free on GitHub?

On GitHub Free, protected branches and rulesets are available for public repositories. For private repositories on a personal account you need GitHub Pro, and for organizations GitHub Team or Enterprise. The settings page shows a notice when a feature is not available on your plan.

Does branch protection stop other people from pushing to my repository?

Other people can never push to your repository unless you add them as collaborators. Outsiders contribute through forks and pull requests that you choose to merge. Branch protection mainly protects you and your collaborators from mistakes such as force pushes, deletions and merging failing code.

Will requiring pull requests break my solo workflow?

It can. If you push directly to main from scripts or alone, a pull request rule will reject those pushes. Either add yourself as a bypass actor, use only deletion and force-push rules, or switch your workflow to short-lived branches with pull requests.

How do I apply branch protection to many repositories?

Use an organization ruleset if your repositories are in an organization. For a personal account, write the ruleset JSON once and apply it to each repository with a short GitHub CLI loop that skips repositories that already have it.

About the author. Saizul Amin is a web developer and technical SEO consultant from Dhaka who manages Ubuntu VPS servers, nginx, Cloudflare, WordPress and n8n in production for his own and client sites. Every command in these guides is one he runs himself; his open-source tools are on GitHub and his client work is at saizul.com.

Sources

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.

Comments are closed.