Automating the Deployment of a React Application with Apache and PHP

Estimated read time 6 min read

Combining React for the front-end, PHP for the back-end, and Apache as the web server provides a robust stack for modern web development. This article will guide you through setting up and automating the deployment of a React application with an Apache server and a PHP backend. By the end, you’ll have automated scripts for building and deploying your React app, configuring Apache, and setting up your PHP backend.

Prerequisites

Before you start, ensure you have the following installed:

  • Node.js and npm: For building the React application.
  • Apache: To serve the React application and PHP scripts.
  • PHP: For handling server-side logic and providing API endpoints.
  • Basic understanding of React, PHP, and Apache configuration.

Step 1: Set Up the React Application

First, create your React application and prepare it for deployment.

1.1 Create a React Application

Use create-react-app to set up a new React project:

npx create-react-app my-app
cd my-app

1.2 Build the React Application

Build the React application to generate static files suitable for deployment:

npm run build

The build output will be in the build directory.

Step 2: Set Up the PHP Backend

Create a PHP script that will serve as your API endpoint or handle server-side logic.

2.1 Create a PHP Script

Create a file named api.php with the following content:

api.php

<?php
header('Content-Type: application/json');

// Example data
$data = [
    ['id' => 1, 'name' => 'John Doe'],
    ['id' => 2, 'name' => 'Jane Smith']
];

echo json_encode($data);
?>

This script returns a JSON response with sample data.

Step 3: Configure Apache

Configure Apache to serve the React application and PHP scripts.

3.1 Deploy the React Build Files

Copy the contents of the build directory from your React app to the Apache server directory:

sudo cp -r build/* /var/www/html/my-app/

3.2 Set Up Apache Virtual Host

Create and configure an Apache virtual host file to serve the React application and handle PHP scripts.

Create a new configuration file:

/etc/apache2/sites-available/react-app.conf

<VirtualHost *:80>
    ServerAdmin webmaster@mydomain.com
    DocumentRoot /var/www/html/my-app
    ServerName mydomain.com

    <Directory /var/www/html/my-app>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    # Add PHP configuration for handling .php files
    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>

    ErrorLog \${APACHE_LOG_DIR}/error.log
    CustomLog \${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Replace /var/www/html/my-app with the path to your React build directory and mydomain.com with your domain name.

3.3 Enable the Virtual Host

Enable the new virtual host configuration:

sudo a2ensite react-app.conf

3.4 Reload Apache

Apply the changes by reloading Apache:

sudo systemctl reload apache2

Step 4: Handle Client-Side Routing in React

To ensure React Router handles routing correctly, create a .htaccess file in your React build directory.

/var/www/html/my-app/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

Step 5: Automate the Deployment

Automate the setup with scripts to streamline deployment and configuration.

5.1 React Build and Deployment Script

Create a script to automate the build and deployment of your React application.

deploy-react.sh

#!/bin/bash

# Define variables
REACT_APP_DIR="/path/to/your/react-app"
APACHE_DIR="/var/www/html/my-app"

# Navigate to the React app directory
cd $REACT_APP_DIR

# Build the React application
echo "Building React application..."
npm install
npm run build

# Clean the old build files from the Apache directory
echo "Cleaning old build files..."
sudo rm -rf $APACHE_DIR/*

# Copy the new build files to the Apache directory
echo "Deploying new build files..."
sudo cp -r build/* $APACHE_DIR/

echo "Deployment completed."

Make the script executable and run it:

chmod +x deploy-react.sh
./deploy-react.sh

5.2 Apache Configuration Script

Create a script to automate Apache configuration.

setup-apache.sh

#!/bin/bash

# Define variables
VHOST_CONF="/etc/apache2/sites-available/react-app.conf"
APACHE_DIR="/var/www/html/my-app"

# Create Apache virtual host configuration
echo "Creating Apache virtual host configuration..."
sudo tee $VHOST_CONF > /dev/null <<EOL
<VirtualHost *:80>
    ServerAdmin webmaster@mydomain.com
    DocumentRoot $APACHE_DIR
    ServerName mydomain.com

    <Directory $APACHE_DIR>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    # Add PHP configuration for handling .php files
    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>

    ErrorLog \${APACHE_LOG_DIR}/error.log
    CustomLog \${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
EOL

# Enable the new virtual host configuration
echo "Enabling virtual host..."
sudo a2ensite react-app.conf

# Reload Apache to apply changes
echo "Reloading Apache..."
sudo systemctl reload apache2

echo "Apache setup completed."

Make the script executable and run it:

chmod +x setup-apache.sh
./setup-apache.sh

5.3 PHP Deployment Script

Create a script to automate the deployment of your PHP script.

deploy-php.sh

#!/bin/bash

# Define variables
PHP_SCRIPT_SRC="/path/to/your/api.php"
APACHE_PHP_DIR="/var/www/html/my-app"

# Copy PHP script to Apache directory
echo "Deploying PHP script..."
sudo cp $PHP_SCRIPT_SRC $APACHE_PHP_DIR/

echo "PHP script deployment completed."

Make the script executable and run it:

chmod +x deploy-php.sh
./deploy-php.sh

5.4 Master Automation Script

Create a master script to run all the individual setup scripts.

setup-full.sh

#!/bin/bash

# Run individual setup scripts
./deploy-react.sh
./setup-apache.sh
./deploy-php.sh

echo "Full setup completed."

Make the script executable and run it:

chmod +x setup-full.sh
./setup-full.sh

Conclusion

Automating the deployment of a React application with Apache and PHP simplifies the process, reduces the risk of errors, and improves efficiency. By using the provided scripts, you can quickly deploy and configure your application, ensuring that updates and changes are applied consistently.

Feel free to adapt these scripts to fit your specific project requirements and deployment environments. For a more advanced setup, consider integrating these scripts into a CI/CD pipeline using tools like Jenkins, GitHub Actions, or GitLab CI to further streamline your deployment process.

Sponsored Links


Written by Dimitrios S. Sfyris, founder and developer of AspectSoft, a software company specializing in innovative solutions. Follow me on LinkedIn for more insightful articles and updates on cutting-edge technologies.

Subscribe to our newsletter!

Dimitrios S. Sfyris https://aspectsoft.gr/en/

Dimitrios S. Sfyris is a leading expert in systems engineering and web
architectures. With years of experience in both academia and industry, he has published numerous articles and research papers. He is the founder of AspectSoft, a company that developed the innovative e-commerce platform AspectCart, designed to revolutionize the way businesses operate in the e-commerce landscape. He also created the Expo-Host platform for 3D interactive environments.

https://www.linkedin.com/in/dimitrios-s-sfyris/

You May Also Like

More From Author

+ There are no comments

Add yours