类似于 Apache 中的 SetEnv 的 Nginx 变量?

我在 Apache 中使用 SetEnv 设置虚拟主机中的一些变量,然后使用 $_SERVER[the_variable]在 PHP 中恢复这些变量。

现在我转向了 Perl Catalyst 和 Nginx,但 Nginx 的“ env”指令似乎并不相同。没用的。怎么才能做到呢?

这里是背景图片,以防有人可以建议一个更好的方法或我以前的系统不与 Nginx 工作。

  • 我使用同一个应用程序为许多域。所有的数据来自不同的数据库具有相同的结构。
  • 数据库名称在该环境变量中硬编码为虚拟主机。
  • 正如我所知道的数据库名称一样,所有的查询都从第一个查询开始进入到相应的数据库中。
  • 我可以有多个域使用相同的数据库,只包括相同的变量到指令。
98499 次浏览

NGINX doesn't manage your backend processes like apache does, so it can't affect their environments. To set a new $_SERVER PHP variable from NGINX, you need to add a new fastcgi_param entry along with the rest of them. Wherever you're including fastcgi_params or fastcgi.conf.

location / {
...
fastcgi_param   APPLICATION_ENV  production;
fastcgi_param   APPLICATION_CONFIG user;
...
}

but it's for PHP-CGI

You should keep in mind, that nginx doesn't manage php processes like apache does. You should config either php-fpm, or php-cgi, relying what runs php on your server.

php-cgi

...
env[APP_ENV] = production
...

php-fpm

location / {
...
fastcgi_param APP_ENV production;
...
}

The fastcgi_pass socket location needs to come first, then each of the fastcgi_param parameters. You can also list variables in a file in the nginx config folder, then include that file. The include file commonly has the name fastcgi_params. Your environment parameters can be added easily to the php handling block:

        location ~ \.php$ {
fastcgi_pass     unix:/your_sock_location/nginxFastCGI.sock;
fastcgi_param    SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param    APP_ENV production;
include          fastcgi_params;
}

The fastcgi_params file located in the same directory as nginx.conf often looks like this:

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;


fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  HTTPS              $https if_not_empty;


fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;


fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;