How to add additional headers to 302 redirects in Apache?

萝らか妹 提交于 2019-12-05 15:55:55

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.

Fix
<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.

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