Search code examples
php.htaccesshttp-redirectlogging

How to capture and log any 301 redirects (.htaccess) that happen using PHP


I have a bunch of 301 redirects set in my .htaccess file. What I'd like to do is keep track of how many times a redirect is used, so that I can manage them better.

Is there a way to capture and log 301 redirects matches that happen with PHP?

In other words, if the redirect is:

RewriteRule ^about/bozo$ /about [R=301,L]

Is there a way to capture the "about/bozo" every time it happens using PHP? (even though the redirects are handled by htaccess calls, and not by PHP header redirects)


Solution

  • You cannot log a 3xx redirect that is triggered earlier in the request by Apache (eg. in .htaccess) using PHP. The redirect is entirely invisible to PHP.

    You can't use the HTTP Referer to determine if a redirect occurred since the browser preserves the Referer from the initial request (if any).

    Requests that trigger a 3xx redirect should be logged in the server's access log.

    The only way you could do this with PHP is if you mark the redirected URL in some way (perhaps with a query string) and check for this in your PHP script. For example:

    RewriteRule ^about/bozo$ /about?redirected=true [R=301,L]
    

    ... but that maybe undesirable.