How to add additional headers to 302 redirects in Apache?

丶灬走出姿态 提交于 2020-01-02 05:54:46

问题


I have a redirect in Apache config like

Redirect temp /foo.xml http://www.baz.com/foo.xml

I am trying to add an Expire and m-cache headers for a CDN to this 302. This would be trivial in php, but I need to do this in Apache config files.

Normally this is done like this:

ExpiresActive On ExpiresDefault "access plus 10 minutes"

but this only seems to not work for 302 redirects. Any suggestions?


回答1:


Check out the mod_headers module for Apache.

Perhaps something like:

<Location /foo.xml>
   Redirect temp /foo.xml http://www.baz.com/foo.xml
   Header always set ExpiresActive On
   Header always set ExpiresDefault "access plus 10 minutes"
</Location>

I have edited this answer (since it was accepted), adding the always keyword, to reflect what Fix correctly pointed out below.




回答2:


<Location /foo.xml>
   Redirect temp /foo.xml http://www.baz.com/foo.xml
   Header always set ExpiresActive On
   Header always set ExpiresDefault "access plus 10 minutes"
</Location>

to get it working even with HTTP 302 responses (actually, with any HTTP response) ; without the keyword "always", the directive "Header set" works only with success responses, i.e. HTTP 2xx responses.




回答3:


Please note an odd bug in Apache 2.2 (observed in Apache 2.2.15) that makes this difficult if you are using env=HTTPS to control when the Header is being set. For some reason env=HTTPS fails to fire during redirects, even if RewriteCond %{HTTPS} on is used to control the redirect. So in my configuration that enables HTTP Strict Transport Security (HSTS), I use use a RewriteRule to create an environment variable called X_HTTPS that has the same value as the HTTPS, but which is not set to null when env=X_HTTPS is evaluated:

SetEnv HSTS "max-age=31536000; includeSubDomains; preload"

# For some reason in Apache 2.2, HTTPS env variable is not available during redirects
RewriteCond %{HTTPS} on
RewriteRule ^.*$ - [ENV=X_HTTPS:%{HTTPS}]
# Set HSTS Header if the page is delivered via SSL
Header always set Strict-Transport-Security %{HSTS}e env=X_HTTPS

# Redirect SSL-only non-www page to www and quit
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^(.*)$ https://www.%{SERVER_NAME}%{REQUEST_URI} [R=303,L]

# Redirect ANY non-SSL page to SSL
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=303,L]


来源:https://stackoverflow.com/questions/690521/how-to-add-additional-headers-to-302-redirects-in-apache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!