How serve static files in reactjs?

Viewed 814

I have several tasks related to show sitemap.xml, robot.txt, some pdf files.

Client-side the latest reactjs + webpack.

I tried two ways via reactjs and via Nginx on the server.

  1. on the server I added these lines

    location ~ ^/(sitemap.xml) { root /var/www/html/public; }

enter image description here

I tried to add it before and after the main location config but it doesn't work

  1. the second option. I tried to add a route to the main router in reactjs but it doesn't work too, I just get empty page.
3 Answers

Create a .htaccess file at the site root. In your case /html/public

Add this in your .htaccess file, this should take care of the React internal routing. Docs

Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]

Regarding your robots.txt, sitemap.xml and pdf files. Absolute path should work fine, else post more details.

I had he same problem with react js , you can try this, :

server{
    listen 80;
    root /home/user/website/build; # the root document of my react website
    index index.html index.htm index.nginx-debian.html;
    server_name website.com;
    try_files $uri /index.html;
    location /robots.txt {
            alias /home/user/website/build/robots.txt;
    }
}

You can add links as i did in /robots.txt and link them to static files.

The easiest way is to install a package called serve

npm i -g serve

And then serve them using the command (replace the build/ with directory having static files)

serve -s build/
Related