DreamWave DreamWave - 3 months ago 15
Apache Configuration Question

.htaccess with multiple rewrite rules, based on path

I have the following .htaccess, which is not working as expected:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^example.bg$
RewriteRule (.*) http://www.example.bg/$1 [R=301,L]

RewriteCond %{REQUEST_URI} !^/sessiontest\.php$
RewriteCond %{REQUEST_URI} ^/login.* [OR]
RewriteCond %{REQUEST_URI} ^/admin.*$
RewriteRule ^(.*)$ travelpartner.php [L,NC]

RewriteCond %{REQUEST_URI} !^/sessiontest\.php$
RewriteCond %{REQUEST_URI} !^/login.*$
RewriteCond %{REQUEST_URI} !^/admin.*$
RewriteRule ^(.*)$ perla/$1 [L,NC]


What I need is the following:


  1. If the URI is missing the "www" from example.bg, then add it and redirect to www.example.bg

  2. If the URI does not end in "sessiontest.php" and starts with "www.example.bg/login" or starts with www.example.bg/admin, then forward all requets to travelpartner.php

  3. For all other cases, we should forward all requests to a subfolder, called "perla"



However, right now what happens is that we always see the contents of the perla subfolder, even if I open exemple.bg/login

What am I missing here?

Answer

With your current rules I get the infinite redirect loop:

Once the rule No.2 is matched, and the request /login is rewritten to /travelpartner.php, the rewritten request is handed back to the URL parsing engine and the ruleset is run again from the start.

This time, it will match the last segment and be rewritten to /perla/travelpartner.php,and sent back again, and be rewritten to /perla/perla/travelpartner.php, etc...

The fix is to, in the last segment, prevent rewriting if the request starts with /perla or is /travelpartner.php:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^example.bg$
RewriteRule (.*) http://www.example.bg/$1 [R=301,L]

RewriteCond %{REQUEST_URI} !^/sessiontest\.php$
RewriteCond %{REQUEST_URI} ^/login [OR]
RewriteCond %{REQUEST_URI} ^/admin
RewriteRule ^ travelpartner.php [L,NC]

RewriteCond %{REQUEST_URI} !^/sessiontest\.php$
RewriteCond %{REQUEST_URI} !^/login
RewriteCond %{REQUEST_URI} !^/admin
RewriteCond %{REQUEST_URI} !^/perla/
RewriteCond %{REQUEST_URI} !^/travelpartner\.php$
RewriteRule ^(.*)$ perla/$1 [L,NC]