Reputation: 53
I am new in ngnix and I don't understand very well the location directive. I have a website with the folloging configuration:
location / {
rewrite ^(.*)$ /index.php last;
}
#assets
location /web/assets/ {
rewrite ^(/web/assets/.*)$ $1 break;
}
location /web/assets/cache/ {
if (!-f $request_filename) {
rewrite ^/web/assets/cache/(.*)$ /web/assets/cache/index.php last;
}
}
In the website, all requests are redirected to index.php, but there is an "assets" folder that I don't want to redirect (/web/assets/). Inside this folder there is a subfolder called "cache". If any file inside this subfolder is requested and the file doesn't exist, the request is redirected to a php file that create the file and save it in cache. This is useful for example for preprocessed css, js, etc, the files are created the first time they are required.
This configuration works well, but I'd like to send some headers to assets files, according to html5 boilderplate suggestions, for example expires rules for static content (https://github.com/h5bp/server-configs-nginx/blob/master/conf/expires.conf), and when I add these directives:
location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
expires 1M;
access_log off;
add_header Cache-Control "public";
}
# CSS and Javascript
location ~* \.(?:css|js)$ {
expires 1y;
access_log off;
add_header Cache-Control "public";
}
The previous redirection doesn't work. I guest it's because nginx doesn't execute all matches locations but only the first one. My question is how to combine rewrite and header directives in ngnix config.
Upvotes: 1
Views: 140
Reputation: 3406
Each request can only be handled by one location block. Also, the usage of if
is not a good practice. try_files can be much more efficient. Also, you have a rewrite rule that rewrites to the same uri (totally useless).
Allow me to rewrite your conf to what I believe is more efficient for your needs and please lt me know if I got something wrong
#this is just fine as it was
location / {
rewrite ^(.*)$ /index.php last;
}
#web assets should be served directly
location /web/assets/ {
try_files $uri $uri/ @mycache;
}
#this is the mycache location, called when assets are not found
location @mycache {
expires 1y;
access_log on;
add_header Cache-Control "public";
rewrite ^/web/assets/(.*)$ /web/assets/cache/index.php last;
}
#some specific files in the web/assets directory. if this matches, it is preferred over the location web/assets because it is more specific
location ~* /web/assets/.*\.(jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
expires 1M;
access_log off;
add_header Cache-Control "public";
try_files $uri $uri/ @mycache;
}
# CSS and Javascript
location ~* /web/assets/.*\.(css|js)$ {
expires 1y;
access_log off;
add_header Cache-Control "public";
try_files $uri $uri/ @mycache;
}
I may have typos or errors, I don't have means to test right now. Let me know
Upvotes: 1