Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Nginx to serve static files from several sources

I have a Nginx config that works fine and serves static files properly:

location /static/ {
    alias /tmp/static/;
    expires 30d;
    access_log off;
}

But what I want to do now is that if the static file doesn't exist in /tmp/static, Nginx looks for the file in /srv/www/site/static. I am not sure how to achieve that, I have tried a few things with try_files, but I don't know how to properly use it.

like image 724
Flavien Avatar asked Sep 05 '12 00:09

Flavien


People also ask

How do I set Nginx to serve static files?

To serve static files with nginx, you should configure the path of your application's root directory and reference the HTML entry point as the index file.

Is Nginx used for serving static content?

Configure NGINX and NGINX Plus to serve static content, with type-specific root directories, checks for file existence, and performance optimizations.

How static images are served in nginx?

Serving Static Files To deploy the container, use Docker Compose. The Docker Compose output. Your static folder and all of its contents are now being served at http://localhost:8080/ using Nginx running inside Docker. Our static files being served on port 8080.

How do you serve static content?

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.static.


2 Answers

You can set your root to the common prefix of the two paths you want to use (in this case, it's /), then just specify the rest of the paths in the try_files args:

location /static/ {
  root /;
  try_files /tmp$uri /srv/www/site$uri =404;
  expires 30d;
  access_log off;
}

It may seem disconcerting to use root / in a location, but the try_files will ensure that no files outside of /tmp/static or /srv/www/site/static will be served.

like image 109
kolbyjack Avatar answered Nov 12 '22 21:11

kolbyjack


the following should do the trick:

location /static/ {
  expires 30d;
  access_log off;
  try_files tmp/static/$uri tmp/static/$uri/ tmp/static2/$uri tmp/static2/$uri/;
}

see http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files for documentation and examples of try_files use

like image 36
cobaco Avatar answered Nov 12 '22 19:11

cobaco