hosting-laravel-and-react-apps-ec2-with-subdomain

🛠️ Hosting Laravel and React Apps on the Same EC2 with Subdomain

Overview

This guide explains how to host a Laravel app on the main domain (e.g., example.com) and a React app on a subdomain (e.g., react.example.com) on the same Apache web server in an EC2 instance.


✅ Prerequisites

curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install nodejs -y
node -v
npm -v

1. 🏗️ Build the React App

If you're using Create React App: npm run build

If you're using Vite: npm run build

This will generate a build/ or dist/ directory inside your React project.


2. 📂 Upload React App to EC2

Create a new directory for your React app: sudo mkdir -p /var/www/react-app

Copy the contents of the build/ or dist/ folder to the EC2 instance using scp or Git:

scp -r build/ ec2-user@your-ec2-ip:/var/www/react-app


3. ⚙️ Configure Apache Virtual Hosts

Laravel VirtualHost (example.com)

Make sure you already have this configured:

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/html/public

    <Directory /var/www/html/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

React VirtualHost (react.example.com)

Create a new Apache config file if needed, e.g., /etc/apache2/sites-available/react.example.com.conf:

<VirtualHost *:80>
    ServerName react.example.com
    DocumentRoot /var/www/react-app

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

    ErrorLog ${APACHE_LOG_DIR}/react_error.log
    CustomLog ${APACHE_LOG_DIR}/react_access.log combined
</VirtualHost>

Enable the site and reload Apache:

sudo a2ensite react.example.com.conf sudo systemctl reload apache2


4. 🌐 Configure DNS

Go to your DNS provider (e.g., AWS Route 53) and add an A record:


5. 🔒 Secure with SSL (Let's Encrypt)

Install Certbot:

sudo apt update sudo apt install certbot python3-certbot-apache

Run Certbot to enable HTTPS:

sudo certbot --apache

Follow the prompts to enable SSL for both domains (example.com and react.example.com).


6. 🔁 Restart Apache

sudo systemctl restart apache2


✅ Final Result

Domain App Location
https://example.com Laravel App /var/www/html/public
https://react.example.com React App /var/www/react-app