So you want to deploy your React app to a Linux server with Apache2..
In this guide, we make the following assumptions: You have an app called react-app and you want to deploy to server your-server.com and the package manager on your server is apt.
From your local react app folder, run the following command to create a chunked version ready for deployment, into a folder called build(npm) or dist(vite).
// from your local machine
npm run build
Now we want to get the contents of your build or dist folder over to your apache server, using scp or ftp or similar. for example:
// from your local machine
scp -r build admin@your-server.com:/home/your-username/
The rest of the steps we will run from your remote server, your-server.com**
Create a folder to serve your app's build files from.
mkdir /var/www/react-app
Move the contents of the build folder inside this new dir.
mv -r /home/your-username/build/* /var/www/react-app
Now we will set up Apache to serve your app from this folder. First, ensure Apache2 is installed and enabled.
sudo apt install apache2 -y
sudo systemctl enable apache2
sudo systemctl reload apache2
You can check your apache install by visiting your-server.com in a web browser, and you should see a default Apache landing page.
Now, Let’s configure apache to serve your app from our /var/www/react-app folder. Apache config files by default live in /etc/apache2/sites-available and are symlinked to /etc/apache2/sites-enabled.
cd /etc/apache2/sites-enabled
sudo cp 000-default.conf react-app.conf
sudo nano react-app.conf
Place the below content into react-app.conf. For the purpose of this guide we aren't thinking about HTTPS.
<VirtualHost *:80>
DocumentRoot /var/www/react-app
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory /var/www/react-app>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>
Create a file /var/www/react-app/.htaccess with the below contents:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
And correct the permissions of your app's files for apache:
sudo chown -R www-data:www-data /var/www/react-app/
Finally, reload apache2. Your react app is now accessible at your-server.com!
systemctl reload apache2