'How to cancel existing runs when a new push happens on GitHub Actions, but only for PRs?

Based on the documentation (there's also a SO answer), I wrote this:

on:
  push
concurrency:
  # Documentation suggests ${{ github.head_ref }}, but that's only available on pull_request/pull_request_target triggers.
  group: ci-${{ github.ref }}
  cancel-in-progress: true
jobs:
  ...

This creates a separate group for each branch, and cancels builds if there's a later push/force push to a branch. Sadly, this also cancels master builds, which I don't want. On master all commits should complete running, so it's easy to see when something broke.

I'm essentially looking for a way to say:

concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: true
  if: github.ref != 'refs/heads/master'


Solution 1:[1]

You can specify cancel-in-progress based on the default branch:

concurrency:
  group: ${{ github.ref }}
  cancel-in-progress: ${{ github.ref != 'refs/heads/master' }}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1