Nginx Reverse Proxy for Apache – Fix PHP Prompted for Download Instead of Execution

httpdnginx

I am trying to make Nginx as a reverse Proxy for Apache on a centos 7 server.

Here is what I did until now:

Create a config file for Nginx: nano /etc/nginx/conf.d/default.conf

server {
    listen   80; 

    root /usr/share/nginx/html/; 
    index index.php index.html index.htm;

    server_name _; 

    location / {
    try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {

    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:8080;

     }

     location ~ /\.ht {
            deny all;
    }
}

Change 2 lines in /etc/httpd/conf/httpd.conf:

Listen 127.0.0.1:8080
DocumentRoot "/usr/share/nginx/html/" 

I created a file named info.php in /usr/share/nginx/html, and put <?php infophp();?> in it, but when I try to load the page http://My_Ip/info.php I get a pop up to download the file, whereas I want the file to be executed.

I passed this command httpd -M | grep php to see if the Php module is present in my apache web server, and I get "php7_module (shared)", so I guess it is.

Any help would be appreciated, thanks.

Henry

p.s: when I go on http://My_IP I get the default Nginx home page
p.s2: fot those who ask, I already posted about a related problem on serverfault (error 403), but it appears that I don't have the problem anymore (i.e if I go to see http://My_IP/any_css_file.css for instance, it well displayed, no error)

Best Answer

You need to have an instance of PHP FPM running on your server to execute the php scripts. You can check by running

find / -type d -iname *fpm*

If this returns some results then it's already installed. Now to find out the port/socket it's listening on you can run:

find / -type d -iname *fpm* | xargs grep -r "^listen[= ]"

Which should return something like this:

/etc/php/7.2/fpm/pool.d/www.conf:listen = /run/php/php7.2-fpm.sock

In your Nginx config directory (usually /etc/nginx/) you may already have a file fastcgi_params, if not then create one and copy the example here

Then change your php location block to include your config file and pass the request to php fpm using the port/socket returned from the command before, like this:

location ~ \.php$ {
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        include fastcgi_params;
    }

Now restart Nginx and it should work.