× {{alert.msg}} Never ask again
Receive New Tutorials

Nginx Tutorial: Serving Static Content Without Using a Directory

– {{showDate(postTime)}}

Codementor PHP expert mentor Chris Fidao is a PHP developer who runs Servers for Hackers, the newsletter about servers, for programmers. He recently sat down with us during Codementor’s office hours to talk about how to use Nginx with your web apps, and he took some time to answer viewers’ questions during Q&A. Here is one of the questions he answered:

The text below is a summary done by the Codementor team and may vary from the original video and if you see any issues, please let us know!

How static content can be served without having just a single directory containing it all?

This is a good site which documents pretty much all the pitfalls and wrong things that I’ve ever done in Nginx. @proxy is a great way to avoid using a static directory. You don’t need define a directory just for static content. For any URI in this setup, it will try to find the file or URI as a directory, and if that fails, instead of responding with a 404 error it sends the request to @proxy and then we name a location block called @proxy.

server {
     server_name example.org;
     root /var/www/site;
     location / {
         try_files $uri $uri/ @proxy;
     location @proxy {
         include fastcgi.conf;
         fastcgi_pass unix:/tmp/php-fpm.sock;

We use the @proxy symbol in the location block to capture everything, and it uses try_files to try to find the file at the directory that it exists in. Failing that, it sends to this location block named @proxy, and then just behaves as normal to proxy the request off to your application. This way you can have static files all over the place. As long as you don’t have an issue where you have a static file which happens to be named a route in your application, this is a perfectly good use for not having to have a specific directory for static assets.

Other posts in this series with Chris Fidao:

Chris FidaoNeed Chris’s help? Book a 1-on-1 session!

or join us as an expert mentor!

Chris Fidao
Chris Fidao
I'm a web (Python, PHP, Golang) developer, primarily working within the Laravel community. I run Servers for Hackers, the newsletter (12000+ subscribed) about servers, for programmers.
Hire the Author

Questions about this tutorial?  Get Live 1:1 help from PHP experts!
Stefan Georg
Stefan Georg
Senior Full Stack Software Developer
I've been coding since age of 15, starting with perl, moving to php, and finally to python. I've been a freelancer working in the US, New Zealand,...
Hire this Expert
Shivam Mathur
Shivam Mathur
Full-Stack Developer
I'm a full-stack software developer. I have consulted for, designed and developed a number of websites and apps. I have experience of shipping...
Hire this Expert
comments powered by Disqus