Nginx SetEnvIf Host

nginxsetenv

Previous server was running on Apache but now i have switched to Nginx.
It's all working great except i don't know how to convert this Apache line in to my working nginx config

SetEnvIf Host "^([^\.]+)\.my-shop\.dev$" MY_ENV=$1

What it needs to do is, that it needs to read the fist "param/subdomain/something" and set is as environment variable

So far i'm trying to achieve this by doing something like this, but it's not working

server {
        listen   80 ;

        server_name $\.my-shop\.dev;

        location ~* \.php$ {
                try_files $uri $uri/ /index.php?q=&$args;
                fastcgi_pass unix:/run/php/php7.0-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
                fastcgi_param MY_ENV $1;
        }
}

If you need any additional informations please let me know and i will provide. Thank you!

Best Answer

to capture the leading part of your shop's subdomain you can use something like this:

server {
        listen   80 ;

        # match and catch the subdomain part in $prefix for later usage:
        server_name   ~^(?<prefix>.+)\.my-shop\.dev$;

        location ~* \.php$ {

                [...] # removed for better readability

                # add MY_ENV env variable to the value of earlier captured $prefix:
                fastcgi_param MY_ENV $prefix;
        }
}

This is explained with more details and other usecases in http://nginx.org/en/docs/http/server_names.html#regex_names