Monday, February 16, 2026

How To Deploy a React Application with apache on Ubuntu

 

To deploy a React application with Apache on Ubuntu, you need to
build your application for production, configure Apache to serve the static files, and ensure proper handling of client-side routing using an .htaccess file.
 
Prerequisites
  • An Ubuntu server with Apache installed.
  • Node.js and npm installed on your local machine or server.
  • A React application ready for deployment.
Step-by-Step Guide
 
 
1. Build the React Application
On your local machine, navigate to your project's root directory in the terminal and run the build command to generate production-ready static files:
bash
npm run build
This command creates an optimized build (or dist if using Vite) folder containing your static assets.
2. Prepare the Ubuntu Server and Upload Files
 
Connect to your Ubuntu server via SSH and prepare a directory to host your application.
  • Create a directory for your site (replace yourwebsite.com with your domain or desired folder name):
    bash
    sudo mkdir -p /var/www/yourwebsite.com
    
  • Set ownership of the directory:
    bash
    sudo chown -R $USER:$USER /var/www/yourwebsite.com
    
  • Upload the contents of the local build folder to the server's directory (e.g., /var/www/yourwebsite.com) using an FTP client like FileZilla or scp.
 
3. Configure Apache for React Routing
 
React applications use client-side routing, which means direct access to sub-routes (e.g., ://yourwebsite.com) will result in a 404 error without proper server configuration. Apache needs to be instructed to redirect all requests to the index.html file.
  • Enable the mod_rewrite module:
    bash
    sudo a2enmod rewrite
    
  • Create a .htaccess file: Inside your application's root directory on the server (e.g., /var/www/yourwebsite.com), create a file named .htaccess and add the following snippet:
    apache
    Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]
    
    This snippet tells Apache that if a requested file does not exist, it should load index.html.
  • Ensure AllowOverride All is set: You might need to edit your Apache configuration to allow .htaccess files to override settings.
    • Open your virtual host file or the main apache2.conf file (e.g., /etc/apache2/sites-available/000-default.conf or /etc/apache2/apache2.conf).
    • Find the <Directory /var/www/html> block (or your custom directory block) and ensure AllowOverride is set to All:
    apache
    <Directory /var/www/yourwebsite.com>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
4. Restart Apache
 
After making configuration changes, restart Apache for them to take effect:
bash
sudo systemctl restart apache2
Your React application should now be deployed and accessible via your server's IP address or domain name.

No comments:

Blog Archive

Followers