APACHE SetEnv directive (from .htaccess) not send to CGI process

I don't understand Apache2 mecanism in this scenario :

1/ In this location : var/www/cgi-bin/ (user's group rights : www-data) i've a CGI script (php-cgi) who will execute PHP app + VAR environement version :

#!/bin/bash
# file : var/www/cgi-bin/cgi-php
exec "/usr/bin/php-cgi$PHP_VERSION"

This script have : chmod a+x executed at runtime by user www-data (Apache server)

All PHP versions are located in :

/usr/bin/php-cgi5.6

/usr/bin/php-cgi7.0

/usr/bin/php-cgi7.1

/usr/bin/php-cgi7.2

All versions working fine.

2/ In Apache Server .conf file, i use :

<Directory "/var/www/cgi-bin">
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Require all granted
    AllowOverride All
</Directory>

SetEnv PHP_VERSION 7.1
ScriptAlias /cgi-bin-php/ /var/www/cgi-bin/
Action php-cgi /cgi-bin-php/php-cgi
AddHandler php-cgi .php

When Apache2 restart i can see in http : PHP Version 7.1 loaded (works fine).

3/ If in .htaccess file i put another PHP_VERSION variable, this not sent ??

File : /var/www/html/.htaccess

SetEnv PHP_VERSION 5.6

In this case .htaccess file do nothing at all. In http i can see : PHP Version 7.1

Question : Why SetEnv PHP_VERSION X.X at runtime is working (when i start Apache2).

And why i can't set a new variable (SetEnv PHP_VERSION X.X) from .htaccess file ? I think Apache won't send $PHP_VERSION variable to the shell environment (Ubuntu Server 16.04).

If anyone can help me... Thanks a lot.

Source : https://www.codejam.info/2014/08/apache-get-php-version-from-environment.html


Solution 1:

I followed the steps outlined in the source link you provided and was able to get it to work with some slight modification. For starters, you want to make sure that the directory your placing that .htaccess file in is configured so that AllowOverride lets it work, otherwise it'll just silently fail.

Secondly, since you're running PHP as a CGI, if you were to drop a phpinfo page and check variables being set you would see your problem. Assuming your variable is successfully being set by your .htaccess file, it's going to be passed in a modified fashion:

_SERVER["REDIRECT_PHP_VERSION"] 

If you just modify your /var/www/cgi-bin/cgi-php file to look for the REDIRECT_PHP_VERSION variable (like exec "/usr/bin/php-cgi$REDIRECT_PHP_VERSION"), then that will likely work. Alternatively (according to this source), if you use fastcgi then you don't have to worry about the variable name changing. If none of that works, then I'd start with a phpinfo page and see what variables are being passed (if at all) and work from there.

Edit: just noting that my test environment where this worked was on a fresh install of httpd on a CentOS 7 server and using SCL versions of PHP and just modifying the paths accordingly.