[ACCEPTED]-How to add additional headers to 302 redirects in Apache?-http-status-code-302

Accepted answer
Score: 17
<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 4 (actually, with any HTTP response) ; without 3 the keyword "always", the directive "Header set" works 2 only with success responses, i.e. HTTP 2xx 1 responses.

Score: 4

Please note an odd bug in Apache 2.2 (observed 10 in Apache 2.2.15) that makes this difficult 9 if you are using env=HTTPS to control when the Header 8 is being set. For some reason env=HTTPS fails to 7 fire during redirects, even if RewriteCond %{HTTPS} on is used 6 to control the redirect. So in my configuration 5 that enables HTTP Strict Transport Security 4 (HSTS), I use use a RewriteRule to create 3 an environment variable called X_HTTPS that has 2 the same value as the HTTPS, but which is not 1 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]
Score: 1

Check out the mod_headers module for Apache.

Perhaps 3 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 2 (since it was accepted), adding the always keyword, to 1 reflect what Fix correctly pointed out below.

More Related questions