• Home
  • Jobs
  • Courses
  • Teachers
  • For business
  • Blog
  • ES/EN

0

40
Views
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)

about 1 month ago ·

Santiago Trujillo

2 answers
Answer question

0

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.

about 1 month ago · Santiago Trujillo Report

0

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.

about 1 month ago · Santiago Trujillo Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.