简体   繁体   中英

PHP & .htaccess redirection loop [does header(location: url) consult .htaccess?]

I'm currently forwarding all requests to a single .php file:

Options +FollowSymLinks
Options -Multiviews
Options All -Indexes

RewriteEngine On
RewriteRule ^(.*)$ urls.php [L,QSA]

For simplicity, lets say the urls.php page is as follows:

<?php
    if(condition) {
        header( "Location: index.php" );
    } else {
        header( "Location: somewhere.php" );
    }
    die();
?>

When a request is made, it enters a redirect loop, I assume this is because it's a never ending loop from urls.php to the page it redirects to and back again.

Questions:
-> Does the header() function always consult the .htaccess file, or is there a way to skip it and go directly to the url?
-> If it always consults it, is there a different PHP approach that I could use to achieve what I want?

Instead of redirect you should you should extract url and route accordingly by using 'include' function. You can apply your logic before routing.

Every HTTP request makes the server read the .htaccess file.

To answer your questions:

  1. Yes, header() outputs an HTTP 301 header which generates another request.
  2. SOLUTION is to include() the corresponding page instead of redirecting to it using header() .

Note:
As @goldlife pointed out in a comment, your rule and page together generate a loop because:

  1. url.php redirects to index.php using the header() function
  2. index.php , in turn, is rewritten by your .htaccess to url.php

To break this loop, you should drop one of the two operations (I vote for dropping the first one).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM