Php – Modify the HTTP status code after PHP has finished generating a response

apache-2.2httpPHPredirect

Does anyone know if it's possible to configure apache to modify the HTTP status code of a response after it has been generated?

Basically, I have a script running under multiple host names that redirects users to a dynamically determined location using a 302 status code, which is generated by the script itself (i.e. a PHP script which sets a 'Location' header). What I want to do is change the status code from 302 to 301 for just one of the host names, while keeping the rest using 302, and I want to do it at the server configuration level so that the script need not be modified.

I've had a look around the apache manual and found mod_headers, but it doesn't seem to be able to modify the status code of a response, only the headers that follow it. Can anyone tell me if there is there a way to do this, or am I stuck with my only option being to modify the script?

Best Answer

You can use mod_rewrite to accomplish this, i.e with the following example:

RewriteCond %{HTTP_HOST} site2.com
RewriteCond %{REQUEST_URI} !^/site2.com
RewriteRule ^(.*)$ site2.com/$1 [R=301,L]

Placing an .htaccess under the hostname you want to redirect will make this work. You can also modify your vhost configuration as well. Don't forget RewriteEngine On if not set already.