argon
argon

Reputation: 449

htaccess - how to compare environment variables - check if 2 environment variables are the same

I need to do redirection if the values of 2 custom-defined environment variables are not identical.
Searching for any way to this on the web, or StackOverflow has been dismal .. been at it for hours now and found nothing that does this simple thing.

This is what I have so far, but it does not work, at all:

RewriteCond %{ENV:HREFBASE} !^$
RewriteCond %{ENV:PATHSTEM} !^%{ENV:HREFBASE}$
RewriteRule ^ %{REQUEST_SCHEME}://%{HTTP_HOST}/%{ENV:HREFBASE}%{REQUEST_URI} [R=302,L]

The part that is obviously wrong is this:

%{ENV:PATHSTEM} !^%{ENV:HREFBASE}$

I've tried several ways, but nothing seems to work.

Any input would we appreciated and rewarded in kind; thanks in advance.

UPDATE

I've even tried this:

RewriteCond %{ENV:HREFBASE} ^$
RewriteRule ^ - [L]

<If "%{ENV:PATHSTEM} != %{ENV:HREFBASE}">
    RewriteRule ^ %{REQUEST_SCHEME}://%{HTTP_HOST}/%{ENV:HREFBASE}%{REQUEST_URI} [R=302,L]
</If>

I can see that the variables do not compare by catching a condition with PHP and printing out the entire $_SERVER array; the part that matters for this is:

[HREFBASE] => anon
[PATHSTEM] => Proc

-which shows clearly that they are not the same, but the redirect does not happen.

Upvotes: 3

Views: 641

Answers (1)

anubhava
anubhava

Reputation: 785276

RewriteCond doesn't allow use of variables on right hand side. But there is a workaround for achieving this comparison by combining both variables into one and using a negative condition to assert equality.

RewriteCond %{ENV:HREFBASE}#%{ENV:PATHSTEM} !^([^#]+)#\1$
RewriteRule ^ %{REQUEST_SCHEME}://%{HTTP_HOST}/%{ENV:HREFBASE}%{REQUEST_URI} [R=302,L,NE]
  • Here we are combining both variable with a known delimiter # in between.
  • ^([^#]+)# matches value till # and captures value before # in group #1.
  • \1$ then matches back-reference of group #1
  • Note that ! before ^ negates this comparison thus giving effectively this comparison:
    %{ENV:HREFBASE} != %{ENV:PATHSTEM}

Upvotes: 2

Related Questions