2

I have a React app built using Vite that I intent to serve on Nginx at www.example.com/myapp

I've set basename in the React Router to /myapp and have set the "homepage": "/myapp" in package.json and it works great when I run vite dev server - the site is correctly scoped and served at localhost:5173/myapp.

However after running vite build and copying to my NGinx server, the linking doesn't work. Here is the location config which is based off this answer ...

location ^~ /myapp {
        // ...
        index index.html;
        alias /home/ubuntu/myrepo/dist;
        try_files $uri $uri/ /myapp/index.html =404;
}

Weirdly, in the logs it does seem to be resolving to another root, /usr/share/nginx/html/myapp/index.html when there is not reference to /usr/share/nginx/html in any of my config.

It doesn't work though. I can only guess it is becuase create-react-app does something different to vite build?

Brendan
  • 18,771
  • 17
  • 83
  • 114
  • It probably has no effect, but any reason to have `index index.html;` twice? Also where is `/home/ubuntu/myrepo/dist` in relation to `/usr/share/nginx/myapp`? Is `/home` really the root path? Inside `home` run `pwd` and see if it starts at `/home` or something else? – Wesley LeMahieu Feb 20 '23 at 19:05
  • My mistake re `index.html` it isn't actually in there twice - `/home/ubuntu/myrepo/dist` is the repository in the `ubuntu` user home directory where the files are kept – Brendan Feb 20 '23 at 19:16

1 Answers1

1

There were a couple of issues ...

Firstly, the resolving to another root was a red-herring - it turns out my NGinx config didn't have a resolver for non-HTTPS connections and I was connecting using http://.... To resolve this I just loaded the page with https://....

Secondly, after a bit of digging, I found the base setting for vite which only applies for building. This means the config looks like this ...

export default defineConfig({
  plugins: [react()],
  base: '/myapp'
})

I also had to update some of my asset references when I was self-building the URL. I used import.meta.env.BASE_URL to get the stem. e.g.

const srcUrl = `${import.meta.env.BASE_URL}/assets/myimg.png

Hope that helps someone else

Brendan
  • 18,771
  • 17
  • 83
  • 114