How to configure Nginx as a reverse proxy for Apache on CentOS

Install and Configure Nginx

Run an update on your repositories list first:

yum update -y

Now install Epel repository easily with:

yum install epel-release -y

Then install nginx using the command below:

yum install nginx -y

Enable and start Nginx service:

systemctl enable nginx systemctl start nginx

Configure Nginx

Create a config file with the following command:

nano /etc/nginx/conf.d/default.conf

Paste the following configuration in your file then save and exit:

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;
        }
}

Install and Configure Apache

If you have Apache already installed you can skip this section.

install Apache web server with the command below:

yum install httpd

Start and enable the httpd service:

systemctl enable httpd systemctl start httpd

Configure Apache

We need to configure the Apache to take the backend part of the job, for that cause we need to configure the Apache to listen on port 8080:

nano /etc/httpd/conf/httpd.conf

Find the line that starts with “listen” remove it and paste the following lines instead:

 Listen 127.0.0.1:8080

Then find the line that starts with “DocumentRoot” and modify it like below:

DocumentRoot "/usr/share/nginx/html/"                                          

The “DocumentRoot” should be the same on both Nginx and Apache, If you have VirtualHost(s) configured, it should be configured on both of them.

Save and Exit.

Install PHP5

You can install PHP5 easily with the command below:

yum install php

Testing your PHP

In this section we are going to test if our PHP is functioning properly and more importantly if it’s processed by the Apache Handler:

create a PHP file in your document root using the following command:

nano /usr/share/nginx/html/info.php

Paste the following code in it then save and exit:

<?php phpinfo(); ?>

Now you can open your browser and enter your Domain or your Public IP address

About Liêm Phan 163 Articles
Mình lập blog này với mục đích lưu lại + chia sẻ các các kiến thức mình đã biết hoặc đang tìm hiểu. Cơ bản giúp ích cho mình :) Nhưng hy vọng sẽ mang lại sự khởi đầu thuận lợi cho người mới bắt đầu!