|
| 1 | +#!/bin/sh |
| 2 | +set -eu |
| 3 | + |
| 4 | +CONTENT_DIR="/usr/share/nginx/html" |
| 5 | +# Allow overriding the served base path at runtime (default /) |
| 6 | +BASE_PATH="${DRAWDB_BASE_PATH:-/}" |
| 7 | + |
| 8 | +if [ -z "$BASE_PATH" ]; then |
| 9 | + BASE_PATH="/" |
| 10 | +fi |
| 11 | + |
| 12 | +# Reject absolute URLs; only relative paths are supported |
| 13 | +case "$BASE_PATH" in |
| 14 | + http://*|https://*) |
| 15 | + echo "DRAWDB_BASE_PATH must be a relative path (e.g. /drawdb)" >&2 |
| 16 | + exit 1 |
| 17 | + ;; |
| 18 | +esac |
| 19 | + |
| 20 | +# Ensure the path has a single leading slash and no trailing slash |
| 21 | +if [ "$BASE_PATH" != "/" ]; then |
| 22 | + BASE_PATH="/${BASE_PATH#/}" |
| 23 | + BASE_PATH="${BASE_PATH%/}" |
| 24 | +fi |
| 25 | + |
| 26 | +# Derive helper variants used by the templated replacements below |
| 27 | +if [ "$BASE_PATH" = "/" ]; then |
| 28 | + BASE_PATH_WITH_SLASH="/" |
| 29 | + BASE_PATH_NO_LEAD="" |
| 30 | + BASE_PATH_NO_LEAD_WITH_SLASH="" |
| 31 | +else |
| 32 | + BASE_PATH_WITH_SLASH="$BASE_PATH/" |
| 33 | + BASE_PATH_NO_LEAD="${BASE_PATH#/}" |
| 34 | + BASE_PATH_NO_LEAD_WITH_SLASH="${BASE_PATH_NO_LEAD}/" |
| 35 | +fi |
| 36 | + |
| 37 | +# Replace the placeholder base path in built assets, if present |
| 38 | +if grep -R "__BASE_PATH__" "$CONTENT_DIR" >/dev/null 2>&1; then |
| 39 | + find "$CONTENT_DIR" -type f \( -name '*.js' -o -name '*.css' -o -name '*.html' -o -name '*.json' -o -name '*.txt' \) -print0 | |
| 40 | + while IFS= read -r -d '' file; do |
| 41 | + sed -i \ |
| 42 | + -e "s|/__BASE_PATH__/|${BASE_PATH_WITH_SLASH}|g" \ |
| 43 | + -e "s|/__BASE_PATH__|${BASE_PATH}|g" \ |
| 44 | + -e "s|__BASE_PATH__/|${BASE_PATH_NO_LEAD_WITH_SLASH}|g" \ |
| 45 | + -e "s|__BASE_PATH__|${BASE_PATH_NO_LEAD}|g" \ |
| 46 | + "$file" |
| 47 | + done |
| 48 | +fi |
| 49 | + |
| 50 | +# Generate Nginx configuration matching the selected base path |
| 51 | +if [ "$BASE_PATH" = "/" ]; then |
| 52 | + cat >/etc/nginx/conf.d/default.conf <<'EOF' |
| 53 | +server { |
| 54 | + listen 80; |
| 55 | + server_name _; |
| 56 | + root /usr/share/nginx/html; |
| 57 | +
|
| 58 | + location / { |
| 59 | + try_files $uri $uri/ /index.html; |
| 60 | + } |
| 61 | +} |
| 62 | +EOF |
| 63 | +else |
| 64 | + cat >/etc/nginx/conf.d/default.conf <<EOF |
| 65 | +server { |
| 66 | + listen 80; |
| 67 | + server_name _; |
| 68 | + root /usr/share/nginx/html; |
| 69 | +
|
| 70 | + location = $BASE_PATH { |
| 71 | + return 301 $BASE_PATH/; |
| 72 | + } |
| 73 | +
|
| 74 | + location $BASE_PATH/ { |
| 75 | + rewrite ^$BASE_PATH/(.*)$ /\$1 break; |
| 76 | + try_files \$uri \$uri/ /index.html; |
| 77 | + } |
| 78 | +} |
| 79 | +EOF |
| 80 | +fi |
| 81 | + |
| 82 | +exec "$@" |
0 commit comments