Refactor nginx configuration handling for dynamic subfolder support and improve asset caching

This commit is contained in:
Tudor Stanciu 2025-09-29 01:28:55 +03:00
parent caf38d468f
commit 4a4dc2af4f
3 changed files with 41 additions and 8 deletions

View File

@ -35,14 +35,13 @@ RUN if [ -n "$APP_SUBFOLDER" ]; then mkdir -p /usr/share/nginx/html/$APP_SUBFOLD
# Copy built application
COPY --from=builder /app/build /usr/share/nginx/html/${APP_SUBFOLDER}
# Copy and configure nginx
COPY nginx.conf /tmp/nginx.conf.template
# Generate nginx.conf with correct subfolder path
RUN if [ -n "$APP_SUBFOLDER" ]; then \
sed "s|# SUBFOLDER_PLACEHOLDER|location /$APP_SUBFOLDER/ { try_files \$uri \$uri/ /$APP_SUBFOLDER/index.html; }|g" /tmp/nginx.conf.template > /etc/nginx/nginx.conf; \
else \
sed "s|# SUBFOLDER_PLACEHOLDER||g" /tmp/nginx.conf.template > /etc/nginx/nginx.conf; \
fi
# Copy nginx configuration files
COPY nginx/nginx.conf /tmp/nginx.conf.template
COPY nginx/configure-nginx.sh /usr/local/bin/configure-nginx.sh
RUN chmod +x /usr/local/bin/configure-nginx.sh
# Generate nginx.conf with correct subfolder configuration
RUN /usr/local/bin/configure-nginx.sh
# Add environment variables
ENV Author="Tudor Stanciu"

34
nginx/configure-nginx.sh Normal file
View File

@ -0,0 +1,34 @@
#!/bin/sh
# Configure nginx.conf based on APP_SUBFOLDER environment variable
# This script generates the appropriate nginx configuration for SPA deployments
TEMPLATE_FILE="/tmp/nginx.conf.template"
OUTPUT_FILE="/etc/nginx/nginx.conf"
if [ -n "$APP_SUBFOLDER" ]; then
echo "Configuring nginx for subfolder deployment: /$APP_SUBFOLDER/"
# Generate location block for subfolder with proper static assets handling
SUBFOLDER_CONFIG=" # Subfolder-specific configuration for /$APP_SUBFOLDER/
location /$APP_SUBFOLDER/ {
# Handle static assets in subfolder
location ~* /$APP_SUBFOLDER/.*\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|json)$ {
expires 1y;
add_header Cache-Control \"public, immutable\";
try_files \$uri =404;
}
# SPA routing for subfolder
try_files \$uri \$uri/ /$APP_SUBFOLDER/index.html;
}"
# Replace placeholder with subfolder configuration
sed "s| # SUBFOLDER_PLACEHOLDER|$SUBFOLDER_CONFIG|g" "$TEMPLATE_FILE" > "$OUTPUT_FILE"
else
echo "Configuring nginx for root deployment"
# Remove placeholder for root deployment
sed "s| # SUBFOLDER_PLACEHOLDER||g" "$TEMPLATE_FILE" > "$OUTPUT_FILE"
fi
echo "Nginx configuration generated successfully"