Nginx – How to Use Nginx Gzip, Cache, and SSL at the same time

nginxnode.js

I'm currently using Nginx with NodeJs and i'm trying to edit my nginx.conf file to allow caching.

With my current setup below I have SSL and GZIP working, but how can I add caching?
I get an error 404.
My files have the following structure: /root/Poplive/Dec5/public

In public I have a file (main-built.js) and the folders (/javascripts|/css), these are the files and folders im trying to cache.

What I tried….

1) I put the directive below inside location / {} in my nginx.conf below

location ~* /.*\.(/javascripts|main-built.js)$ {
expires 24h;
}

Result, no caching but GZIP works

Nginx.conf below

events { worker_connections 1024; }
http {

    upstream myapp {
        server 127.0.0.1:3100;
    }

#Add Gzip
    sendfile        on;
    keepalive_timeout   2;
    tcp_nodelay        on;
    gzip  on;
    gzip_http_version 1.1;
    gzip_vary on;
    gzip_comp_level 5;
    gzip_proxied any;
    gzip_types text/plain text/css application/json json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;
    gzip_buffers 16 8k;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";

    server {
        root /Poplive/Dec5/public;

        ssl_certificate /root/Poplive/Dec5/server.crt;
        ssl_certificate_key /root/Poplive/Dec5/server.key;

        listen 80;
        listen 443 ssl;
  if ($ssl_protocol = "") {
    rewrite ^ https://$host$request_uri? permanent;
  }
        server_name poplive.co;





           location / {

 location ~* /.*\.(/javascripts|main-built.js)$ {
    expires 24h;
    }

proxy_set_header X-FORWARDED-PROTO https;
            proxy_pass http://myapp/;

     }

    }
}

Best Answer

Your regex is incorrect. I don't know what you want exactly, but I can still confirm it's incorrect.

location ~* /.*\.(/javascripts|main-built.js)$ {

Here's what wrong with that.

  • If you want / character, you should escape it by using \. so it looks like \/
  • When you wrote \.(MoreRulesHere), that meant you want files like .main-built.js. But you aren't going to name your files like that, are you?
  • By putting $ at the end, you stated that /javascripts should be the ending. That is, it's a request of a folder.

I believe you meant to write (assuming since I can't exactly tell your intent).

location ~* \/(javascripts\/.*|main-built.js)$ {

That is everything in javascripts folder and a file called main-built.js. Because there is no ^ character at the beginning, it does not state that it needs to begin with above. So, it will match things like /something/else/here/javascripts/foo as well.