× {{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!
javascript enthusiast with a taste for all new web technologies.
I have been programming on various web and cross platform stacks for 5 years. I love making things and helping people build things. If you need...
Hire this Expert
RajhaRajesuwari S
RajhaRajesuwari S
Full Stack PHP /Angular js web developer
I am an experienced full stack developer 11 years in the field with consistent knowledge in developing web portals with expertise in all opensource...
Hire this Expert

Live 1:1 help from expert developers

Codementor is your live 1:1 expert mentor helping you in real time.

comments powered by Disqus