Running PHP behind proxy

It is a common requirement to have your web applications run behind a proxy. For instance, your application might need to access some resource which are not directly accessible, or it might need authentication to access the Internet, or you might just want to log all outgoing requests. In any case, running an application behind proxy is usually straight forward. All that is needed is to export some environment variables.

HTTP_PROXY and HTTPS_PROXY environment variables

To run a web application behind a proxy, we need to export two environment variables, HTTP_PROXY and HTTPS_PROXY. It usually takes the format:

export HTTP_PROXY=http://<proxy_host>:<proxy_port>
export HTTPS_PROXY=https://<proxy_host>:<proxy_port>

Additionally, if your proxy server requires authentication, you can pass the username and password along with the URL like

export HTTP_PROXY=http://<username>:<password>@<proxy_host>:<proxy_port>
export HTTPS_PROXY=https://<username>:<password>@<proxy_host>:<proxy_port>

While such a proxy configuration works for most programs, like cURL, python, nodejs, golang etc. surprisingly, it does not work for PHP. After some fiddling I found that for PHP, the environment variable name needs to be in lower case. Thus for PHP we will need to export:

export http_proxy=http://<username>:<password>@<proxy_host>:<proxy_port>
export https_proxy=https://<username>:<password>@<proxy_host>:<proxy_port>

It is to be noted that exported variables are only available within the shell in which they are exported. To make it available to all processes through out the server append the above lines to /etc/environment file.

Leave a comment

Your email address will not be published. Required fields are marked *