inrob
inrob

Reputation: 5089

nginx browser caching directive brings 404 not found

One of the sites I want to implement browser caching for images has this particular server {} block on virtual.conf

server {

    listen       80;
    server_name www.example.net  example.net;

    location / {
        root   /var/www/example.net/public_html;
        index  index.html index.htm index.php;
    }

    error_page  404              /404.html;
    location = /404.html {
        root   /var/www/example.net/public_html;
    }

    # redirect server error pages to the static page /50x.html
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /var/www/example.net/public_html;
    }

    location ~*  \.(jpg|jpeg|png|gif)$ {
       expires 180d;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
        root           /var/www/example.net/public_html;
        error_log      /var/www/example.net/public_html/error.log error;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    } 
}

Normally this directive

    location ~*  \.(jpg|jpeg|png|gif)$ {
       expires 180d;
    }

Should take care of caching images on the user end. But instead when I access an image on my website I get 404 not found. I am not sure why this I caused.

Yes. I reloaded/restarted nginx after adding the directive.

The image resides in a subfolder like:
example.net/images/dir1/user_photos/photo.jpg
or
example.net/images/dir1/user_photos/photo.jpg

Any help would be appreciated. Thank you.

Upvotes: 3

Views: 1144

Answers (1)

Harpreet Ahy
Harpreet Ahy

Reputation: 11

Root parameter should be outside the location directive.

It is not the best practice to have root inside location

Change

 location / {
        root   /var/www/html;
        index index.php  index.html index.htm;
        try_files $uri $uri/ /index.php?$args;
 } 

To:

 root   /var/www/html;
 location / {
        index index.php  index.html index.htm;
        try_files $uri $uri/ /index.php?$args;
 }

Upvotes: 1

Related Questions