Nginx - Serve static html content with whitespace in filename
I use this setting to serve static html files:
server {
root /var/www/static_html;
index index.html index.htm;
location / {
try_files $uri $uri/index.html $uri.html =404;
autoindex on;
}
}
Now if a filename contains whitespace "spam spam.html"
the response is "404 Not Found"
In the access.log:
"GET /spam%20spam.html HTTP/1.1" 404
Is it possible to serve these files?
Solution 1:
I bumped into the same issue when trying to setup NGINX to serve WebP files from the same filename as JPG/PNG's and certain files were containing spaces. The reason why it happens like this is:
- space cannot be used inside of an URL and browsers replace it automatically inside the URL with
%20
, as you might be aware - the
$uri
variable in this case will contain the link with%20
as you can see from the logs - when NGINX is looking for the file with
%20
in its name on the disk, it will not find it, because on disk it is stored with space and not with%20
, therefore it will result in a 404.
A potential way of getting this to work is to do a replacement of the %20
with a space and the only way of achieving this that comes to my mind is to use something like OpenRestly's Lua NGINX Module:
https://github.com/openresty/lua-nginx-module
Then, after this is properly installed and configured (not very easy!), you might try something like this, just before try_files
:
access_by_lua_block {
ngx.var.uri = string.gsub(ngx.var.uri, "%20", " ")
}
This isn't actually tested, it's just an idea. If there are better ways to achieve this, I'm open to check them!