Score:0

NGINX - How to serve file with filename that begins with the last segment of uri?

ng flag

I have many PDFs in a \drawings folder on my server. The filename structure is: 8 digits, underscore, Rev level letter -- i.e. \d{8}_[A-Za-z]\.pdf. These files are organized in subfolders that match the first 4 digits of the filename -- \drawings\1500\, \drawings\1600\ etc.

I want users to be able to call up a drawing in the browser, not knowing the REV level, by using just the first 8 digits. e.g.

intranet.com/drawings/15003915 -> Z:\drawings\1500\15003915_D.pdf

intranet.com/drawings/16000423 -> Z:\drawings\1600\16000423_B.pdf

in nginx.conf, I have the following

location ^~ /drawings/ {
  try_files $uri @redirect;
}

location @redirect {
  if ($uri ~* "^/(\d{8})$") {
    set $filename $1;
    rewrite ^/(.*)$ Z:/Drawings/${$uri:1:4}/$filename_[A-Z].pdf last;
  }
  return 404;
}

NGINX regex has always thrown me. I keep getting errors on the rewrite line.

Ideas on how to fix?

Richard Smith avatar
jp flag
You regex is wrong, but that's not the issue here. Nginx cannot guess the filename, and has no mechanism to use wildcards on the filesystem like your shell does. If there are 26 possible values, you will need a very ugly and slow solution that tests every possibility. It would be better to set up a symbolic link pointing to the latest version.
ng flag
@RichardSmith That's what I was afraid of. Files are generated by 3D CAD software, the process is ongoing, and there's no good way I'm aware of to create symlinks for every one on the fly (there are thousands).
ppenguin avatar
tr flag
@SeanO: Some possibilities (ugly workarounds but possible given the unfavourable constraints): a cron-like (timed) service updating the symlinks; a script that watches the drawing dirs with `inotify` and makes symlinks when it sees a new file was written. These solutions are easiest linux-based, since you appear to be on windows you may need similar alternatives. But I guess if you implement them in e.g. python it may have the necessary abstractions.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.