大网数据广告活动
服务器运维问答

Apache server – trying to use Location directive in .htaccess

· 52CE 我爱测

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 "/fo…

问题原文

原帖链接 · TBJ · CC BY-SA 4.0

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.

已采纳解答

原帖链接 · MrWhite · CC BY-SA 4.0

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/$#"

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-12-10)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。