2

I need to remove all caching when a specific path (/foo/bar/) is called on my website. My managed hosting support tells me that I should do this in .htaccess and I have tried to use the Location directive, like so:

<Location "/foo/bar/">
  Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
</Location>

But all I get is an internal server error. Did I leave something out or should this directive be placed in a certain place in .htaccess. I have tried everything I can think of, with the same result.

Ola Ström
  • 177
  • 1
  • 1
  • 6
TBJ
  • 171
  • 1
  • 8

2 Answers2

3

As has already been mentioned, the <Location> directive is not permitted in .htaccess files. If /foo/bar/ relates directly to a filesystem directory then you can place the .htaccess file in that directory to apply the directives (Header in this case) to that directory and below only.

However, if /foo/bar/ is a URL-path only (which is also what the <Location> directive targets in a server context), which does not relate directly to the filesystem, then you can instead set an environment variable when that URl-path is accessed and set the Header conditionally based on whether that env var is set.

For example:

SetEnvIf Request_URI "^/foo/bar/$" NO_CACHE
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate" env=NO_CACHE

The above sets the env var NO_CACHE (to the value 1) when the URL-path /foo/bar/ (only) is requested and the Header directive is then only applied when that env var is set (by the last argument env=NO_CACHE).


Alternatively, if you are on Apache 2.4+ then you can use Apache <If> expressions to directly target that URL-path only, negating the need to set an env var. For example:

<If "%{REQUEST_URI} =~ m#^/foo/bar/$#">
    Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
</If>

Another alternative, if you are on Apache 2.4.10+ then you can use an Apache expression directly in the Header directive in order to target that URL-path only. For example:

Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate" "expr=%{REQUEST_URI} =~ m#^/foo/bar/$#"
MrWhite
  • 12,647
  • 4
  • 29
  • 41
0

According to the Apache documentation, the Location directive cannot be used in .htaccess file at all. You can use Location in the server config, but the .htaccess file always refers to the current directory in which the file resides, so specifying directives for another location in that file is pointless.

Simply leave the Location directive out, the Header itself should work for that directory / location.

Lacek
  • 7,233
  • 24
  • 28