简体   繁体   中英

How to set HTTP Header only for existing files using in Apache conf

I'm serving files and app requests using Apache, App requests use RewriteRule to send urls that match a pattern to my app servers.

I'd like to set a particular HTTP header (Cache-control) only for requests that don't match the RewriteConds from above. Is there any way of doing that without using an .htaccess file?

I've tried placing the Header set directive AFTER the RewriteRule (which uses the L flag) but the header still gets applied.

You should really post your rewriteRules.

There is certainly something we can do for that. First thing I'm thinking is setting an environment variable in matching rewriteRules (so a set of rewriteCond, inverting the previous ones), use the [E=myvar:myvalue] tag; and use the last available argument of the Header instruction [env=myvar] to conditionnaly set this Header.

Then you said:

Is there any way of doing that without using an .htaccess file?

Well, RewriteRules and .htaccess files are loosely related. Anything you set in a .htaccess would really fit better in a <Directory> instruction with a nice AllowOverride None on your VirtualHost to prevent a looooot of IO operations from apache, trying to read a bunch of .htaccess files at each requests.

Second thing, you said:

I've tried placing the Header set directive AFTER the RewriteRule (which uses the L flag)

Well the [L] flag prevent several RewriteRules on the same directory to be applied one after the other, so they won't be chained right now direclty. But in fact after your rewriteRule ends ([L]) the output of the rewriteRule is then reapplied on the directory, to see if any RewriteRule (maybe the same one) should still be applied.

This is why we sometimes see too much Internal redirections messages.

The only way to see it happen is to use the RewriteLog /a/file.log and RewriteLogLevel 9 on the VirtualHost (a lot of surprises sometimes, some rules are sometimes working with a lot too much recursions).

A good RewriteCond to known for that is :

RewriteCond %{ENV:REDIRECT_STATUS} ^$

Any rule prefixed with this rewriteCond will only be applied thefirst time you enter the directory, after the end of your rules (maybe with an [L] or because there is not more rule) the result will be re-tested on the direcory rules but with an env variable REDIRECT_STATUS not empty. This Condition tell mod-rewrite to avoid the rule if this env variable is set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM