Nginx – How to Serve NextJS Static Assets

nginxproxypassreverse-proxystatic-files

I have a NextJS app running on port 3000 and I have a test.ico file located at the following location:

/static/images/icons/

I want this file to be served off the root rather than the actual path. I mean instead of https://www.schandillia.com/static/images/icons/test.ico, I want it to be available as https://www.schandillia.com/test.ico. I can easily configure my Express server to serve this file but I want to let Nginx handle this. So I have the following configuration added to my Nginx conf server block:

location / {
    proxy_pass http://127.0.0.1:3000;
    charset UTF-8;
    proxy_http_version 1.1;
  }
  location /test.ico {
    proxy_pass http://127.0.0.1:3000/static/images/icons/test.ico;
    expires 365d;
    add_header Pragma public;
    add_header Cache-Control "public";
  }
  location ~* \.(?:ico|svg|woff|woff2|ttf|otf|css|js|gif|jpe?g|png)$ {
   proxy_pass http://127.0.0.1:3000;
   expires 365d;
   add_header Pragma public;
   add_header Cache-Control "public";
  }

However, https://www.schandillia.com/test.ico is now throwing a 404. What am I doing wrong?

Best Answer

The regular expression location takes precedence over regular prefix location blocks. See this document for details.

You can change the precedence order by using any of these instead:

location = /test.ico
location ^= /test.ico
location ~ ^/test.ico