DEV Community

Cover image for Deploy ReactJs website on Apache server (Hostgator) with Vite
Luiz Vicente
Luiz Vicente

Posted on

Deploy ReactJs website on Apache server (Hostgator) with Vite

Why on earth deploy to Apache/Hostgator?

To see if it works. That simple.

And does it work? Of course it works, but it needs a few things to make it work properly.

Let's go from the beginning

It's a simple website, but it will be in a subfolder. For example:
https://mydomain.com/site2

Having defined this, chances are that you use a Router (react-router-dom, TanStack Router, etc.). I use react-router-dom a lot, so this case is no different.

Configs

package.json

As the website will be in a subfolder, you need to add the homepage tag to your package.json file, otherwise the build will assume that your project is hosted in the root of the server.

{
  ...
  "homepage": "https://mydomain.com/site2/",
  ...
}
Enter fullscreen mode Exit fullscreen mode

BrowserRouter config

Add the basename prop to the BrowserRouter:

import { BrowserRouter } from 'react-router-dom';
import { Router } from './routes/Router';

export const App = () => {
  return (
    <BrowserRouter basename='/site2'>
      <Router />
    </BrowserRouter>
  )
}
Enter fullscreen mode Exit fullscreen mode

vite.config.js

Without this step, no matter what you do, when you run vite build, the generated index.html file will have the wrong link references. Therefore, this configuration is crucial.
All you need to do is add the base option in the vite.config.js file:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  base: '/site2/',
  plugins: [react()],
})
Enter fullscreen mode Exit fullscreen mode

Or via the vite build --base=/my/public/path/ flag.

Finally, just run the build. In my case, I use pnpm:

pnpm run build
Enter fullscreen mode Exit fullscreen mode

Configuring Apache

Right. But for all of this to work online, you still need to configure Apache, using the .htaccess file.

You need to have this file in the folder where the index.html will be located. Therefore, create the file in the folder, in my case, /site2, with the following content:

RewriteEngine On
RewriteBase /site2
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [L]
Enter fullscreen mode Exit fullscreen mode

Finally, upload the files from your project's dist folder to your Apache folder. Don't forget the files in the assets folder.

That's it!

Top comments (0)