Nginx Reverse SSL Proxy with PHP

This trick introduce the way of creating nginx reverse SSL proxy that works with PHP in load balancing environment.

Example network structure


  1. Nginx proxy config file for ssl connection
    define upsteam in nginx.conf

upstream{ ip_hash; server max_fails=3 fail_timeout=8; server max_fails=3 fail_timeout=8; server max_fails=3 fail_timeout=8; }

define the

server { listen 443; server_name; index index.php index.html index.htm; ssl on; ssl_certificate /etc/ssl/; ssl_certificate_key /etc/ssl/; ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!ADH:!MD5:!aNULL:!eNULL:!MEDIUM:!LOW:!EXP:!kEDH; ssl_session_timeout 10m; ssl_prefer_server_ciphers on; proxy_set_header Cookie $http_cookie; location / { proxy_pass; #here is the upstreams that defined in upsteam block proxy_next_upstream error timeout invalid_header http_500; proxy_connect_timeout 2; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; add_header Front-End-Https on; } }

  1. Web server behind the proxy
    2.1. Install pecl_http extension with pecl install pecl_http. (This extension allow you to obtain headers from cgi mode, ideally for php-fpm)

2.2. In PHP script, use

if($_SERVER['HTTP_X_FORWARDED_PROTO']'https' || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] ! 'off')){ //SSL detected }

To check if the request is from https