.htaccesshttp-redirectredirect-loop

RewriteCond %{ENV:REDIRECT_STATUS} 200 Not Working


I am writing 301 redirect first time...

Objective

I have to redirect any URL

to: www.example.com/product/item

item can have values like iphone-6-black-3g (having hyphen in them)

htaccess-code

I have made a test project and the following is in the htaccess file:

RewriteEngine on
RewriteBase /test/

RewriteCond %{ENV:REDIRECT_STATUS} 200 ### i have tested for ^.
RewriteRule ^ - [L]

RewriteRule ^(.+)/([^\-]+)-(.+)/?$  $2/$3.php?cat=$2&item=$3 [L,R=301]

If I redirect to test.php?cat=$2&item=$3 it is showing correct values in $2 and $3.

Problem

But if I redirect it to $2/$3.php weird things happen.

Since the new URL generated also satisfy the rule so I think a loop occurs that continue until no more match....

To break the loop I have added %{ENV:REDIRECT_STATUS} 200, but it looks like it is not working.

I am getting crazy... the only solution coming to my head is change the item format like apple_iphone-t etc... Having first underscore and then hyphen. in this way no loop

Kindly suggest if we can solve it with hyphen pattern?


Solution

  • You could just prevent the loop by adding some conditions:

    RewriteEngine on
    RewriteBase /test/
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)/([^\-]+)-(.+)/?$  $2/$3.php?cat=$2&item=$3 [L,R=301]
    

    The reason why %{ENV:REDIRECT_STATUS} isn't working is because you are using an external redirect. You're redirecting the browser so the browser sends a whole new request, so there's no internal redirecting for that condition to work.