Nginx Tutorial: Serving Static Content Without Using a Directory
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:
- PHP Office Hours: How to Use Nginx With Your Web Application
- Nginx & Node.js vs Apache
- Things You Need to Take Care of When Setting Up a New Server