Nginx – How to Force Serve File if File Exists

nginx

I want check if file exists in custom location (outside of root)
force serve this file ,else rewrite index.php

the file locations depends on the subdomain and url path:

url : http://my.subdomain.mysite.com/location/of/file.css

file path: /tmp/cache/my.subdomain/location/of/file.css

my site-available:

server {
    listen 80;
    server_name mysite.com ~([\w\.]+)\.mysite\.com$ ;
    set $subdomain $1;
    root /var/www/site/web;
    index index.php index.html;

    location / {

            set $cacheDir /tmp/cache;
            set $cacheFile "${cacheDir}/${subdomain}/${request_uri}";

            if (-f $cacheFile) {
              ?????
              ????? what do I write here?
              ????? 
            } 

            include         snippets/fastcgi-php.conf;
            include         fastcgi_params;
            fastcgi_param   SCRIPT_FILENAME  $document_root$fastcgi_script_name;
             .
             . 
             .
        }
 }

Best Answer

Well, if you really want to do this, try

location / {

    set $cacheDir /tmp/cache;
    set $cacheFile "${cacheDir}/${subdomain}${uri}";

    if (-f $cacheFile) {
        root "${cacheDir}/${subdomain}";
    }

}

location ~ \.php$ {
    # your fastcgi config here
}

Please note that nginx access to /tmp/cache may be blocked by default SELinux policies.