Serving openGym under a subpath works, with or without the prefix reaching the container (#238)

The app's assets were already relative — the shell loads fine from any directory, which is how
the demo lives under /demo/. What assumed the site root was the API call: `fetch('/api/...')`
went to the proxy's own root, where there is nothing to answer it, so behind
`https://example.com/gym/` the app booted and then could not talk to its server.

It now asks its own address instead: `appBase()` reads the directory the app is being served
from, which the router never leaves — every screen is a hash, and a path that is not a file is
sent back to the app's root before React boots. A proxy that strips its prefix (Caddy's
`handle_path`, Traefik's StripPrefix) therefore needs no configuration at all.

For a proxy that passes the prefix through, the web container takes `BASE_PATH=/gym`, rendered
into its nginx config at start-up like the other settings, so it applies to a prebuilt image.
Wired through docker-compose.yml as well — a documented setting the compose file does not pass
on is no setting at all.

Both shapes were checked in containers rather than read: with BASE_PATH empty the shell, the
assets, /api and the deep-path redirect behave exactly as before; with BASE_PATH=/gym all four
work under the prefix and the redirect stays inside it. The first attempt passed at /gym/ and
404'd /gym/assets/app.js, because a regex location outranks the prefix block and never saw its
rewrite — the cache-control blocks carry it too now. The built app was then loaded in a browser
under /gym/ and its own requests go to /gym/api/config and /gym/api/me.

Reported by leon332157.
This commit is contained in:
Duarte Santos committed 2026-09-20 20:16:52 +02:00
1 parent f7b9a80a93
commit 542c3f493a
8 files changed
+124 -6

No files matched your search

+7
View File
@@ -113,6 +113,13 @@ RP_NAME=openGym
# NGINX_PORT=80
# BACKEND=api
# PORT=3000
#
# Serving openGym under a subpath (https://example.com/gym/)? If your reverse
# proxy strips the prefix before the container sees it, set nothing — the app
# asks its own address for the API. If it passes the prefix through, name it
# here without a trailing slash:
#
# BASE_PATH=/gym
# ── Notifications (optional) ───────────────────────────────────────────────
# Push works out of the box — nothing to set. VAPID keys are generated on first
+4
View File
@@ -85,6 +85,10 @@ services:
# Empty drops the CF-Connecting-IP header, so a direct client cannot forge the address
# the activity log records. Cloudflare users set CF_CONNECTING_IP=$$http_cf_connecting_ip.
- CF_CONNECTING_IP=${CF_CONNECTING_IP:-}
# Subpath deployments behind a proxy that passes its prefix through ("/gym", no trailing
# slash). Empty serves the app at the site root, which is what it has always done; a proxy
# that strips the prefix needs nothing set (docs/SELF_HOSTING.md §5).
- BASE_PATH=${BASE_PATH:-}
volumes:
- ./media/img:/usr/share/nginx/html/img:ro
- ./media/gif:/usr/share/nginx/html/gif:ro
+35
View File
@@ -182,6 +182,7 @@ NGINX_PORT=80 # port the web container listens on, inside the conta
BACKEND=api # name of the API service that /api is proxied to
PORT=3000 # port the API listens on; web proxies to the same value
RESOLVER=127.0.0.11 # DNS nginx resolves BACKEND with — Docker's, unless you are not on Docker
BASE_PATH= # subpath openGym is served under, e.g. /gym — see below; empty = site root
SESSION_DAYS=90 # how long a sign-in lasts
```
@@ -200,6 +201,40 @@ Note the difference from `VITE_IMG_BASE` / `VITE_GIF_BASE` (see Troubleshooting)
build-time values baked into the frontend bundle, and setting them next to `docker compose` does
nothing to an image you pulled.
### Serving openGym under a subpath
openGym can live at `https://example.com/gym/` rather than on a host of its own. Which of the two
setups below you need depends on one thing: whether your reverse proxy strips the prefix before
the container sees the request.
**The proxy strips the prefix** (Caddy's `handle_path`, Traefik's `StripPrefix` middleware,
nginx `proxy_pass` with a trailing slash). Nothing to configure. The app's assets are relative
and it asks its own address for the API, so everything stays inside the prefix on its own:
```caddy
example.com {
handle_path /gym/* {
reverse_proxy opengym-web:80
}
}
```
**The proxy passes the prefix through.** Tell the web container what it is, without a trailing
slash:
```bash
BASE_PATH=/gym
```
That is a start-up setting like the others above, so it works on a prebuilt image. Forward only
the prefix to the container — openGym does not serve itself at the site root as well, and a copy
reached there would look for an API that is not on that path.
Either way, keep `ORIGIN` and `RP_ID` pointing at the address in the browser's bar
(`ORIGIN=https://example.com`, `RP_ID=example.com`). Passkeys key on the host, not the path, so a
subpath changes nothing about section 2 — but it does mean two instances under one hostname share
a passkey scope and can see each other's credentials. Give each its own hostname if that matters.
## 6. Backups
Everything is in `./data`:
+32
View File
@@ -0,0 +1,32 @@
// @vitest-environment happy-dom
// Issue #238: openGym behind a reverse proxy that serves it under a subpath. The assets were
// already relative; the API call was not, so it went to the proxy's own root where nothing
// answers it. The base is read from where the app is being served.
import { describe, it, expect } from 'vitest'
import { appBase } from './api.js'
const at = pathname => appBase({ pathname })
describe('the app knows where it is served from', () => {
it('is the site root for an ordinary deployment', () => {
expect(at('/')).toBe('/')
expect(at('/index.html')).toBe('/')
})
it('keeps the proxy prefix of a subpath deployment', () => {
expect(at('/myGym/')).toBe('/myGym/')
expect(at('/myGym/index.html')).toBe('/myGym/')
expect(at('/a/b/c/')).toBe('/a/b/c/')
})
it('drops a stale deep path rather than inventing a base from it', () => {
// nginx sends these back to the app root before React boots; this is the belt and braces.
expect(at('/myGym/plan/r/x')).toBe('/myGym/plan/r/')
expect(at('/plan')).toBe('/')
})
it('survives a missing or odd location', () => {
expect(appBase(null)).toBe('/')
expect(at('')).toBe('/')
})
})
+22 -1
View File
@@ -15,10 +15,31 @@ let remoteBase = ''
let remoteToken = null
export function setRemoteAuth(base, token) { remoteBase = base || ''; remoteToken = token || null }
/* Where this copy of the app is served from, e.g. "/" or "/myGym/" (issue #238).
*
* The app routes behind the hash and its assets are relative (vite `base: './'`), so the only
* thing that assumed the site root was the API call. A reverse proxy that puts openGym under a
* subpath — and strips that prefix before the container sees it, which is what Caddy's
* `handle_path` and its equivalents do — got `/api/...` at the proxy's own root, where there is
* nothing to answer it.
*
* `location.pathname` is the base because the router never leaves it: every screen is a hash,
* and a path that is not a file is sent back to the app's root before React boots
* (web/nginx.conf.template). Anything after the last slash is therefore index.html or a stale
* deep link, and is dropped.
*/
export function appBase(loc = typeof location !== 'undefined' ? location : null) {
const path = (loc && loc.pathname) || '/'
return path.slice(0, path.lastIndexOf('/') + 1) || '/'
}
export async function api(path, opts) {
const headers = Object.assign({ 'Content-Type': 'application/json' }, opts && opts.headers)
if (remoteToken) headers.Authorization = 'Bearer ' + remoteToken
const r = await fetch(remoteBase + path, Object.assign({}, opts, { headers }))
// A paired phone has an absolute base of its own; everyone else is relative to where the app
// is served, so a subpath deployment reaches its own API instead of the proxy's root.
const url = remoteBase ? remoteBase + path : appBase().replace(/\/$/, '') + path
const r = await fetch(url, Object.assign({}, opts, { headers }))
const data = await r.json().catch(() => ({}))
// The body rides along on the error: a 409 from /api/data carries the server's document.
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; e.data = data; throw e }
+2 -2
View File
@@ -9,7 +9,7 @@ import { effectiveRoutines, effectiveRoutineIds, lastEntryFor, bestWeightFor, be
import { fmtNum, capWords, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate, unlock } from '../lib/sound.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import { api, appBase } from '../lib/api.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor, warmupRestSecFor } from '../lib/supersetFlow.js'
import Media from '../components/Media.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, renameWorkoutSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet, addRoutineToSessionSheet } from '../sheets.jsx'
@@ -964,7 +964,7 @@ function ActiveWorkout() {
return () => {
stopped = true; clearInterval(iv)
// best-effort "left" signal: sendBeacon survives a tab close, fetch covers in-app nav
try { navigator.sendBeacon?.('/api/activity', new Blob([JSON.stringify({ active: false })], { type: 'application/json' })) } catch { /* */ }
try { navigator.sendBeacon?.(appBase().replace(/\/$/, '') + '/api/activity', new Blob([JSON.stringify({ active: false })], { type: 'application/json' })) } catch { /* */ }
api('/api/activity', { method: 'POST', body: JSON.stringify({ active: false }) }).catch(() => {})
}
}, [])
+4
View File
@@ -58,6 +58,10 @@ ENV RESOLVER=127.0.0.11
# front. Defined here too, not just in compose, so the template always renders for anyone
# running the prebuilt image from their own compose file.
ENV CF_CONNECTING_IP=""
# Subpath deployments behind a reverse proxy that does NOT strip its prefix: "/gym", no trailing
# slash. Empty (the default) serves the app at the root exactly as before. A proxy that strips
# the prefix needs nothing here — the app derives the API address from its own URL.
ENV BASE_PATH=""
# Probe the port nginx was actually told to listen on (NGINX_PORT is configurable, so a
# hardcoded http://localhost/ breaks on any instance that changed it), and address it as
+18 -3
View File
@@ -19,7 +19,7 @@ server {
# `^~` so this prefix beats the regex locations below: without it a request for a path such
# as /api/anything.json would be matched by the \.(js|css|json|html)$ block instead and be
# looked for on disk rather than proxied.
location ^~ /api/ {
location ^~ ${BASE_PATH}/api/ {
# Match the API's own body limit (MAX_BODY in api/server.js): the whole workout history
# travels in one PUT /api/data, and nginx's 1 MiB default would answer 413 here before the
# API ever saw it — a sync that silently stops once the history grows past 1 MiB.
@@ -59,16 +59,28 @@ server {
# under that path and 404'd — blank, with a 200. Send the browser to the root instead. The
# query string travels along; the hash never reaches the server anyway. Relative Location so
# the redirect keeps the scheme and host the reverse proxy in front presented, not nginx's own.
location / {
#
# BASE_PATH (default empty) is for a reverse proxy that serves openGym under a subpath and
# passes that prefix through — "/gym", no trailing slash. A proxy that strips the prefix
# before the container sees it needs nothing set here: the app asks its own address for the
# API (lib/api.js appBase), so the call carries whatever prefix the browser is using.
location ${BASE_PATH}/ {
# `rewrite ... break` rather than `alias`: try_files inside an aliased prefix location is
# a long-standing nginx trap (it still resolves the untranslated URI). With BASE_PATH
# empty this rewrite is an identity and the block behaves exactly as it always has.
rewrite ^${BASE_PATH}/(.*)$ /$1 break;
try_files $uri $uri/ @root;
}
location @root {
absolute_redirect off;
return 302 /$is_args$args;
return 302 ${BASE_PATH}/$is_args$args;
}
# App shell: always revalidate so updates show up immediately
location ~* \.(js|css|json|html)$ {
# A regex location wins over the prefix block above, so it never saw its rewrite and
# looked for the file under the prefix on disk. Same identity-when-empty rewrite here.
rewrite ^${BASE_PATH}/(.*)$ /$1 break;
add_header Cache-Control "no-cache, must-revalidate";
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
@@ -78,6 +90,9 @@ server {
# Exercise images/GIFs never change → cache hard
location ~* \.(png|jpg|jpeg|gif|ico|svg|woff|woff2|webp|avif)$ {
# A regex location wins over the prefix block above, so it never saw its rewrite and
# looked for the file under the prefix on disk. Same identity-when-empty rewrite here.
rewrite ^${BASE_PATH}/(.*)$ /$1 break;
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
add_header X-Frame-Options "DENY" always;