'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 1:[1]

MrWhite's answer is correct that you can't see those redirects in PHP. However, you don't need to use PHP to get the stats you want.

If you want stats on how often those redirects happen, you can get them from your web server's access_log file. Every 301 redirect should add an entry in the log file regardless of whether the redirect was triggered by .htaccess or PHP. Such a log entry should look something like this:

127.0.0.1 - - [01/Jan/2000:11:55:36 -0700] "GET /about/bozo HTTP/1.1" 301 456

You can use command line tools to count redirects:

grep '" 301 ' /var/log/apache2/access_log | wc -l

or

grep 'GET /about/bozo ' /var/log/apache2/access_log | wc -l

Where grep does the filtering of the log file and wc -l counts the lines.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stephen Ostermiller