Django Nginx Browser Caching Configuration

2019-02-26 01:44发布

问题:

I am trying to configure Nginx to leverage on static file caching on browser. My configuration file is as following

server {

    listen   80;
    server_name localhost;

    client_max_body_size 4G;

    access_log /home/user/webapps/app_env/logs/nginx-access.log;
    error_log /home/user/webapps/app_env/logs/nginx-error.log;

    location /static/ {
        alias   /home/user/webapps/app_env/static/;
    }

    location /media/ {
        alias   /home/user/webapps/app_env/media/;
    }
...
}

When I add in the following caching configuration, the server fails to load static files and I am not able to restart my Nginx.

location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 365d;
}

The nginx-error log shows open() "/usr/share/nginx/html/media/cover_photos/292f109e-17ef-4d23-b0b5-bddc80708d19_t‌​humbnail.jpeg" failed (2: No such file or directory)

I have done quite some research online but cannot solve this problem.

Can anyone help me or just give me some suggestions on implementing static file caching in Nginx? Thank you!

Reference: Leverage browser caching for Nginx

回答1:

Again, I have to answer my own question. The root problem lays on the "path".

I find the answer from @Dayo, here I quote:

You are missing the rootdirective for the images location block. Therefore, nginx will look for the files in the default location which varies by installation and since you have most likely not placed the files there, you will get a 404 Not Found error.

Answer from Dayo

Thus, I added the root path in my configuration file as following:

root /home/user/webapps/app_env/;

The whole configuration will look like this:

server {

    listen   80;
    server_name localhost;

    root /home/user/webapps/app_env/;

    client_max_body_size 4G;

    access_log /home/user/webapps/app_env/logs/nginx-access.log;
    error_log /home/user/webapps/app_env/logs/nginx-error.log;

    location /static/ {
       alias   /home/user/webapps/app_env/static/;
    }

    location /media/ {
       alias   /home/user/webapps/app_env/media/;
    }

    location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
       expires 365d;
    }

...
}

And everything just work nice.

I hope people with the same problem can learn from this.