Search code examples
nginxhttp-headersshiny-servercache-control

Setting http headers for caching with shiny server & nginx


I have deployed a shiny app, running with a shiny server on AWS. A nginx server reroutes requests to the shiny server's port 3838.

When checking Google Page Speed Insights (https://developers.google.com/speed/pagespeed/insights/), I see that some images (.webp format) on my page are not cached, and that this slows down the loading of my page.

I tried to set up caching in nginx, as described here, by adding the following lines to my nginx server config:

location ~* \.(js|webp|png|jpg|jpeg|gif)$ {
    expires 365d;
    add_header Cache-Control "public, no-transform"; 
}

However, this had the consequence of my images not being found anymore when accessing the website.

  1. Is is correct that I have to enable caching in nginx and not somewhere in shiny server?
  2. If so, what is wrong with the solution above?

Here is the conf file of nginx without any additions:

server {
    listen 80;
    listen [::]:80;
    # redirect all HTTP requests to HTTPS with a 301 Moved Permanently response.
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    # Reverse proxy
    location / {
        proxy_pass http://localhost:3838/climate-justice/;
        proxy_redirect http://localhost:3838/climate-justice/ $scheme://$host/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 20d;
        proxy_buffering off;
    }

# OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;

}

Solution

  • Solved it with the help of the following instructions: https://www.digitalocean.com/community/tutorials/how-to-implement-browser-caching-with-nginx-s-header-module-on-ubuntu-16-04

    # Expires map
    map $sent_http_content_type $expires {
        default                    off;
        text/html                  epoch;
        text/css                   max;
        application/javascript     max;
        ~image/                    max;
    }
    
    server {
        listen 80 default_server;
        listen [::]:80 default_server;
    
        expires $expires;
    . . .