0

For a specific URL, I'd like to set cache-control headers for static assets such as /images/*, /js/*, etc. that tells the browser to use the local cache for lets say 30 days instead of fetching a new version. How can I accomplish this via haproxy config?

Before this is misunderstood, this is not a duplicate of how to cache contents in HAProxy. I'd merely like haproxy to append headers to requests for certain assets telling the browser to use the local cached version, if available, but only for 1 specific domain.

HBruijn
  • 77,029
  • 24
  • 135
  • 201
Ben
  • 3,800
  • 18
  • 65
  • 96

2 Answers2

2

You could probably accomplish that in one line, but it is clearer like this:

frontend myfrontend
    bind 0.0.0.0:80
    default_backend default
    acl cache_me path_dir /js
    acl cache_me path_dir /images
    use_backend cache if cache_me

backend default
    server server1 1.2.3.4:80

backend cache
    http-request set-header cache-control max-age="2592000"
    server server1 1.2.3.4:80

Explanation:

the acl keyword tells haproxy that it should add the request to a specific acl if the condition hits.

path_dir matches a subdirectory, whereas path would match the entire path. Maybe path_sub is better here, it looks for a substring in the path.

use_backend directs requests to a specific backend if the request is in the ACL. Everything else goes to the default backend.

This way, you can easily add more paths later, or even point those requests to different servers later if you wanted.

Additionally, filtering by domain as well:

frontend myfrontend
    bind 0.0.0.0:80
    default_backend default
    acl cache_me path_dir /js
    acl cache_me path_dir /images
    acl domain1 hdr(host) -m sub example.com
    use_backend cache if cache_me and domain1

backend default
    server server1 1.2.3.4:80

backend cache
    http-request set-header cache-control max-age="2592000"
    server server1 1.2.3.4:80
mzhaase
  • 3,798
  • 2
  • 20
  • 32
0
frontend main
   http-request set-var(txn.path) path

backend local
   http-response set-header X-Robots-Tag noindex if { var(txn.path) -m end .pdf .doc }
HBruijn
  • 77,029
  • 24
  • 135
  • 201
Prabhin
  • 314
  • 2
  • 2
  • 5
    It looks like you may have the knowledge to provide good Answer here, but please consider reading [How do I write a good Answer?](http://serverfault.com/help/how-to-answer) in our help center and then revise the Answer. Your Commands/Code/Settings may technically be the solution but some explanation and context is welcome. And also please use [Markdown](http://serverfault.com/editing-help) and/or the formatting options in the edit menu to properly type-set your posts to improve their readability. Thanks in advance. – HBruijn Aug 13 '18 at 07:28