I am trying to create a generic nginx.conf
that does a proxy_pass
depending on the environment.
I am using fixture from cloud foundry staticfile-buildpack
https://github.com/cloudfoundry/staticfile-buildpack/tree/master/fixtures/pushstate_and_proxy_pass/
I want to set a proxy pass depending on the environment variable.
This is the code of the proxy.conf:
location /api { proxy_pass {{env "MY_DEV_PROXY"}}; }
I expect that MY_DEV_PROXY environment variable that I have previously set is resolved.
Instead, when pushing my app to cloud foundry I get:
ERR 2019/02/19 08:18:39 [emerg] 88#0: directive "proxy_pass" is not terminated by ";" in /home/vcap/app/nginx/conf/includes/proxy.conf:1
When using a direct value instead of a variable:
location /api { proxy_pass https://my-dev-proxy.com; }
everything works fine.
cf curl /v2/info && cf version:
{
"description": "Cloud Foundry provided by Swisscom",
"min_cli_version": "6.42.0",
"min_recommended_cli_version": "latest",
"api_version": "2.128.0",
"osbapi_version": "2.14",
}
cf version 6.42.0+0cba12168.2019-01-10
If you're using the Nginx buildpack, you can use the method in the docs for accessing environment variables.
location /api { proxy_pass {{env "MY_DEV_PROXY"}}; }
https://docs.cloudfoundry.org/buildpacks/nginx/#env
If you're using the Staticfile buildpack, you cannot use the same feature from the Nginx buildpack (at least at the time of writing).
The Staticfile buildpack generates most/all of the Nginx config automatically for you, so you technically shouldn't need to insert any environment variables. However, you can include custom Nginx snippets with the Staticfile buildpack, so it's reasonable to want to access environment variables from those snippets.
If you want to do that, you'd need to do something like this:
See the Custom Location
instructions here. You'll need to set an alternative root
and location_include
in Staticfile
. This will reference and instruct Nginx to process custom config that you supply through the app.
Instead of specifying custom config files, specify custom erb
scripts. Ex: nginx/conf/includes/custom_header.conf.erb
. This should contain your config as a template, but you can reference env variables like <%= ENV["MY_VAR"] %>
. You can also do anything else valid in an erb template.
location /api { proxy_pass <%= ENV["MY_DEV_PROXY"] %>; }
Add a .profile
script to the root of your application. In this script, you'll use erb
to process your template file and generate the actual configuration.
erb nginx/conf/includes/custom_header.conf.erb > nginx/conf/includes/custom_header.conf
When your app starts, it will run this script and turn your template into an actual custom config. Nginx will then load the custom config.
Hope that helps!