Wednesday, May 30, 2012

What happens first? .htaccess or php code?


If I use mod_rewrite to control all my 301 redirects, does this happen before my page is served? so if I also have a bunch of redirect rules in a php script that runs on my page, will the .htaccess kick in first?



Source: Tips4all

7 comments:

  1. When a request is made to the URI affected by the .htaccess file, then Apache will handle any rewrite rules before any of your PHP code executes.

    ReplyDelete
  2. The .htaccess will kick in first. If you look at the Apache request cycle:



    PHP is a response handler. mod_rewrite runs at URI translation, except for rewrite rules in .htaccess and <Directory> or <Location> blocks which run in the fixup phase. This is because Apache doesn't know which directory it's in (and thus which <Directory> or .htaccess to read) until after URI translation.

    In response to to gabriel1836's question about the image, I grabbed it from the second slide of this presentation but it's originally from the book: Writing Apache Modules in Perl and C which I highly recommend.

    ReplyDelete
  3. Yes, the .htaccess file is parsed before your script is served.

    ReplyDelete
  4. htaccess is controlled by the webserver. This file will be taken in account before your PHP file.

    For example, you could restrict access to a particular folder with your htaccess file. So, it have to be take in charge before your PHP.

    Hope this helps.

    ReplyDelete
  5. The .htaccess is performed by Apache before the php script execution.
    (imagine if the php script is executed and then the .htaccess make a redirection to another page...).

    ReplyDelete
  6. You always can test this with the following command:

    wget -S --spider http://yourdomain.com


    With this command you see the who is responding to your request.

    As all the others mentioned, .htaccess is first.

    ReplyDelete