I am looking for a solution for this a problem: I need that every HTTP request (method is irrelevant) in Apache http server would be served only after execution of specific PHP script. This is needed because I need to gather some information about requests, etc. As far as I understand - this could be achieved using mod_rewrite module. So far I have done this (in .htaccess file):

RewriteEngine on
RewriteRule ^(.*)$ script.php [C]

script.php is executed, but I need that after this original request would be executed.

Thanks - any help is appreciated.

  • 1
    Wrong implementation can't have good solution Do you know about include() or require() in PHP? Oct 2, 2011 at 14:50
  • I really can't see a point in this question. Can you add more info? Why this script needs to run before the original request? Can't this be solved using includes, requires or ob_start? Oct 2, 2011 at 15:44
  • I need to get information (IP, method, etc) about request and then let it execute. As far as I know - inculde/require is not good, because it will not handle, for example, 'domain.com/file.txt?param=1'. Oct 4, 2011 at 7:38
  • Oh God when I read this I understand why Internet is such a mess (>_<)" Nov 14, 2011 at 16:11
  • Why not build this into your application put the php function into a header of all your files and before each file is loaded it will get the referring IP and path and execute your script as needed before loading the page.
    – Anagio
    Jun 16, 2012 at 8:57

3 Answers 3



Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^(.*)$ script.php?filename=$1 [L]

make script.php run your code and afterwards redirects using the filename variable you passed to it. ($_GET['filename'])


I've done a similar setup in the past in my 404.php page. I look at the url coming in, and if it matches something I'd expect I would use a LOCATION: header to redirect.

The purpose for this in my case was after a rewrite to the site, magazines, etc. that had linked to either deprecated sections or articles would just die at the 404. I wanted to take them to the correct content or at least a "friendlier" section.

Another use for it was to shorten urls so we could send out


Which didn't exist, so it would die to the 404. My switch/case looked for "special" and could redirect to...


Don't know if that helps... but it's one way to "pre-filter" and redirect traffic.


If you are working with PHP anyway, why not use the auto-prepend-file (see PHP manual) settings. To add it conditionally via .htaccess see this suggestion.

Alternatively, it should be possible to use Apache RewriteRules to call your script via RewriteMap's possibility to call external scripts. (I do not think it is a good idea to do and would not recommend it)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.