Deploy React JS In Subfolder

Author - Bipin

Sometimes it is necessary to run our React project in a path like example.com/sub-url-name. In that case, it’s not wise to change react routes just for it. And there must be some easy way around it in the create-react-app build process. While I was looking for a solution to Deploy Reactjs In Subfolder, I found there is no blog explaining it in full detail. So it is kind of self-documentation and might be helpful to superb react community out there :).

Steps to generate react build to deploy in subfolder

For example, if you have server example.com but you want to run your project at example.com/sub-url-name.
Step : 1
– create .env file
– add public url (your subdirectory name)
PUBLIC_URL=/sub-url-name


Step : 2 (very important for react route)
– open the file in which you have defined <Router>
– add basename on your Router just like below
<Router basename={process.env.PUBLIC_URL}>

Step : 3 (add .htaccess file in your project with this configuration) 

 

<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteBase /sub-url-name/
 RewriteCond %{REQUEST_FILENAME} -s [OR]
 #Rewrite Conditions 
 RewriteCond %{REQUEST_FILENAME} -l [OR]
 RewriteCond %{REQUEST_FILENAME} -d
 RewriteRule ^.*$ – [NC,L]
 RewriteRule ^(.*) /sub-url-name/index.html [NC,L]
 </IfModule>

 

Step : 4
– Run : npm run build
– upload all files of build folder in your server “sub-url-name” folder (this point is also notable as you need to create “sub-url-name” folder in server)

Few notes : If you have not found some files like favicon.ico than just add %PUBLIC_URL% before your file path for the project.
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">


Let me know if I am missing any point so we can add it and can use this blog as one point solution to Deploy React JS in subfolder.

Git for deploy reactjs insubfolder

Free SEO Checker |
Test your website for free with OnAirSEO.com

Get Your SEO report!

Don’t miss the next post!

Loading

Related Posts