Fix: 404 errors for static assets when using CMD_URL_PATH configuration #1943
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
When configuring
CMD_URL_PATH
to serve CodiMD under a subdirectory path (e.g.,CMD_URL_PATH=codimd
), static assets like CSS, JavaScript files, favicons, and other resources return 404 errors, making the application unusable.Example Issue
With the following Docker configuration:
URLs like these would return 404:
http://localhost:3000/codimd/build/font.68d91a5a4c1afd7f82a9.css
→ 404http://localhost:3000/codimd/build/cover.65bca5da2232a62861ce.css
→ 404Root Cause
/
instead of respecting theurlPath
configurationurlPath
prefix/codimd
and/codimd/
Solution
1. Fixed Static Asset and Route Mounting (
app.js
)Added conditional mounting based on
config.urlPath
:2. Fixed Redirect Loop (
lib/middleware/redirectWithoutTrailingSlashes.js
)Updated the middleware to avoid redirect loops by allowing the URL path itself to pass through:
3. Socket.IO Configuration
Updated Socket.IO to use the correct path when URL path is configured:
Testing
Local Configuration Used
Results
/codimd/build/...
/codimd/
/codimd/api/...
Reverse Proxy Compatibility
The fix also works correctly with reverse proxies. Here's a working Caddy configuration:
Key Points for Reverse Proxy Setup:
/codimd
Breaking Changes
None. This is a backward-compatible fix that only affects behavior when
CMD_URL_PATH
is configured.Files Modified
app.js
- Added URL path-aware mounting logiclib/middleware/redirectWithoutTrailingSlashes.js
- Fixed redirect loopFixes issue with 404 errors when using
CMD_URL_PATH
configuration for serving CodiMD under subdirectory paths.