ninja_dev
ninja_dev

Reputation: 393

Nginx configuration behind nginx reverse proxy

I have an Nginx with Docker for my development environment with HTTP and HTTPS, here's the configuration:

listen 80;
listen 443 ssl;

set_real_ip_from 10.0.0.0/8;
real_ip_header X-Real-IP;
real_ip_recursive on;

location / {
    try_files $uri @rewriteapp;
}

location @rewriteapp {
    rewrite ^(.*)$ /app.php/$1 last;
}

location ~ ^/(app|app_dev|app_test|config)\.php(/|$) {
    fastcgi_pass php-upstream;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param HTTPS $https;
}

I want to test HTTP and HTTPS in my local environment but in production, I have an Nginx reverse proxy in front with:

upstream app_upstream {
  server app:80;
}

server {
server_name $APP_DOMAIN;

listen 443 ssl;
ssl_certificate /run/secrets/app_cert.pem;
ssl_certificate_key /run/secrets/app_key.pem;

proxy_set_header HOST $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

location / {
    proxy_pass http://app_upstream;
}
}

I want the reverse proxy to accept the only HTTPS and forward to the application nginx but my PHP application behind is receiving $_SERVER['HTTPS'] = ""

I also want to keep the SSL certificate only on the reverse proxy, how do I pass HTTPS from reverse proxy to Nginx to PHP?

Upvotes: 3

Views: 7420

Answers (1)

Richard Smith
Richard Smith

Reputation: 49692

The HTTPS variable is set to $https (which is set according to the connection to the backend server, which will always be HTTP), but you want it to be set according to the forwarded connection.

You can use the X-Forwarded-Proto header to set the HTTPS variable using a map. For example:

map $http_x_forwarded_proto $https_flag {
    default off;
    https on;
}
server {
    ...
    location ~ ^/(app|app_dev|app_test|config)\.php(/|$) {
        ...
        fastcgi_param  HTTPS  $https_flag;
        ...
    }
}

See this document for more.

Upvotes: 3

Related Questions