Skip to main content

Nginx Enable Cache and Gzip

Enable Image Cache #

Add below settings to your Nginx configuration file

server {
    server_name your-domain.com;

		location /route1 {
				# settings here
    }
    
		location /route2 {
				# settings here
    }
		
    location ~* ^/route1/.+\.(jpg|jpeg|png|gif|ico)$ {
        root /your/image/location;
        try_files $uri $uri/ =404;
        expires 2d;
        add_header Cache-Control "public";
    }
    location ~* ^/route2/.+\.(jpg|jpeg|png|gif|ico)$ {
        root /your/second/image/location;
        try_files $uri =404; # Important to serve static files correctly
        expires 2d;
        add_header Cache-Control "public";
    }
    
    # other settings

}

Explanation of REGEX:

  • ~*: This modifier tells Nginx that this location block should use a case-insensitive regular expression match. The ~ indicates a regular expression match, and the `` makes it case-insensitive. This means that it doesn’t matter if the request is for .JPG or .jpg, both will match.
  • ^: This symbol is used in regular expressions to denote the beginning of a string. In this context, it means the match must start at the beginning of the request URI.
  • /route1/: This part of the pattern specifies the literal path that must appear at the beginning of the request URI right after the ^. So, the request URI must start with /route1/ to match this block.
  • .+: In regular expressions, . matches any single character (except for line terminators), and + means “one or more” of the preceding element. So, .+ matches one or more of any characters, ensuring that there is something after /route1/ before the file extension.
  • \.: The backslash \ is an escape character in regular expressions, used here to indicate that the following dot . is to be treated as a literal dot character rather than the special regex meaning of “any single character.”
  • (jpg|jpeg|png|gif|ico): This is a group, denoted by parentheses (), containing several options separated by the pipe | character, which acts as an “or” operator. This means the URI can end with any one of these file extensions to be considered a match.
  • $: This symbol is used in regular expressions to denote the end of a string. It means the pattern must match right up to the end of the request URI.

Enable Gzip for Files #

Add below settings to your Nginx configuration file

server {
    server_name your-domain.com;

    location / {
        root /your/files/location;
        try_files $uri $uri/ /index.html;

        # Enable gzip compression
        gzip on;
        gzip_vary on;
        gzip_min_length 1000;
        gzip_proxied any;
        gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    }
}