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.comwith your domain or desired folder name):bashsudo 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
buildfolder to the server's directory (e.g.,/var/www/yourwebsite.com) using an FTP client like FileZilla orscp.
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_rewritemodule:bashsudo a2enmod rewrite - Create a
.htaccessfile: Inside your application's root directory on the server (e.g.,/var/www/yourwebsite.com), create a file named.htaccessand add the following snippet:This snippet tells Apache that if a requested file does not exist, it should loadapacheOptions -MultiViews RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.html [QSA,L]index.html. - Ensure
AllowOverride Allis set: You might need to edit your Apache configuration to allow.htaccessfiles to override settings.- Open your virtual host file or the main
apache2.conffile (e.g.,/etc/apache2/sites-available/000-default.confor/etc/apache2/apache2.conf). - Find the
<Directory /var/www/html>block (or your custom directory block) and ensureAllowOverrideis set toAll:
apache<Directory /var/www/yourwebsite.com> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> - Open your virtual host file or the main
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:
Post a Comment