diff --git a/backend/src/app.js b/backend/src/app.js index b6c1bf2..ce77665 100644 --- a/backend/src/app.js +++ b/backend/src/app.js @@ -336,42 +336,54 @@ if (fs.existsSync(frontendDistPath)) { const forwardedHost = req.get('X-Forwarded-Host') || req.get('host'); const baseUrl = `${protocol}://${forwardedHost}`; - logger.info(`HTML rewrite: protocol=${protocol}, host=${forwardedHost}, baseUrl=${baseUrl}`); + logger.info(`HTML rewrite: protocol=${protocol}, host=${forwardedHost}, baseUrl=${baseUrl}, originalHost=${req.get('host')}`); // Replace relative URLs (starting with /) in src and href attributes with absolute URLs // This ensures assets are loaded with the same protocol as the page - html = html.replace(/src="\/([^"]+)"/g, (match, path) => { - // Only rewrite asset paths, not API paths - if (path.startsWith('assets/') || path.startsWith('vite.svg') || path.match(/\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$/)) { - return `src="${baseUrl}/${path}"`; - } - return match; - }); + // Match: src="/assets/..." or href="/assets/..." or src="/vite.svg" etc. + const assetPatterns = [ + /src="\/(assets\/[^"]+)"/g, + /href="\/(assets\/[^"]+)"/g, + /src="\/(vite\.svg)"/g, + /href="\/(vite\.svg)"/g, + ]; - html = html.replace(/href="\/([^"]+)"/g, (match, path) => { - // Only rewrite asset paths, not API paths - if (path.startsWith('assets/') || path.startsWith('vite.svg') || path.match(/\.(css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$/)) { - return `href="${baseUrl}/${path}"`; - } - return match; + assetPatterns.forEach(pattern => { + html = html.replace(pattern, (match, path) => { + const newUrl = `${baseUrl}/${path}`; + logger.info(`Rewriting ${match} to ${newUrl}`); + // Replace the entire match with the new absolute URL + if (match.includes('src=')) { + return `src="${newUrl}"`; + } else if (match.includes('href=')) { + return `href="${newUrl}"`; + } + return match; + }); }); // Also replace any absolute HTTP URLs with HTTPS if request is HTTPS if (protocol === 'https') { html = html.replace(/href="http:\/\/([^"]+)"/g, (match, url) => { - if (url.includes(host)) { - return `href="https://${url}"`; + if (url.includes(forwardedHost) || url.includes(req.get('host'))) { + const newUrl = match.replace('http://', 'https://'); + logger.info(`Converting HTTP to HTTPS: ${match} -> ${newUrl}`); + return newUrl; } return match; }); html = html.replace(/src="http:\/\/([^"]+)"/g, (match, url) => { - if (url.includes(host)) { - return `src="https://${url}"`; + if (url.includes(forwardedHost) || url.includes(req.get('host'))) { + const newUrl = match.replace('http://', 'https://'); + logger.info(`Converting HTTP to HTTPS: ${match} -> ${newUrl}`); + return newUrl; } return match; }); } + logger.info(`HTML rewrite completed. HTML length: ${html.length}`); + res.send(html); }); });