kempchee
kempchee

Reputation: 470

Conceptual Rails / nginx

I would like nginx to serve static assets instead of rails in production. Following railscasts I set up the nginx.conf file to include:

root /public

location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
} 

location / {
proxy_pass @rails_app #defined elsewhere
}

I get what this is doing: If the request matches the pattern then serve it directly from the root and add the appropriate headers. What I don't understand is how the request is generated. If I send some dynamic url: /thing/1, then nginx will proxy_pass this to the rails app which will send back a response. Now suppose that response needs an image. Rails won't serve images in production(in my setup), so nginx must serve it. But how does nginx know to serve it? I know a separate request is generated for that image that will match the image location directive and so avoid the proxy_pass, but when/where is that request generated? Does the initial rails response tell the browser to make an additional request for the image, or does rails make the request itself directly to nginx?

Upvotes: 1

Views: 63

Answers (1)

Anatoly
Anatoly

Reputation: 15530

Nginx looks for the most matching result through defined locations tree. The first lookup is for "=" locations, if there is no matching, it goes further. Next is "^~" with "/" and root the following.

The best example can be found here in official docs: http://nginx.org/en/docs/http/ngx_http_core_module.html#location

In your case, all requests matching "/assets/" go directly to file system bypassing Rails application. Rest calls served by proxy pass.

Upvotes: 1

Related Questions