context
I am using nginx and a simple prefix match to serve a single page application. To match the business' style guidelines the url should be hyphenated (https://host.tld/my-app
).
I am using the nginx docker image as the base so my (partial) server config is very simple:
server {
listen 80;
root /usr/share/nginx/html;
location /my-app {
root /usr/share/nginx/html/my-app;
try_files /$uri /$uri.html /$uri/ /index.html =404;
}
}
The production assets exist within /usr/share/nginx/html/my-app
.
edit: I've just discovered that this issue only occurs when running my container locally i.e. when the host is localhost and the port is mapped. my configuration appears to work in production. still, I am curious as to why this would be happening.
problem
when I use the location prefix above (with hyphen) my browser appears to receive the incorrect files for various requests. For example:
Uncaught SyntaxError: Unexpected token '<'
in main.71992375.chunk.js:1
syntax errors caused by interpreting html as javascript
by inspecting the file main.71992375.chunk.js:1
I actually see the contents of my index.html
wrong files served with hyphen in location
I have experimentally determined that simply changing the location prefix to use an underscore (https://host.tld/my_app
) resolves the issue entirely.
correct files served with underscore in location
attempted solutions
here are some solutions I tried (though none resolved the issue to my satisfaction)
- use a regular expression match
location ~ /my[-]app {
(same symptom - wrong files served at expected urlhttps://host.tld/my-app
) - changed root directory not to use a hyphen (was worried that nginx failed on this case but it appears to make no difference)
- use an underscore (correct files served, but not a solution as I am required to use a hyphen)
ask
please let me know what I am doing wrong here. surely there is a way to use hyphenated locations with nginx. many thanks in advance!