Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup apache server for React route?

I have my react app running great on my local dev server but it did not work when I dump my production ready files straight into Apache's htdocs directory:

Here is what I have:

/var/www/index.html /var/www/bundle.js 

and I have

DocumentRoot /var/www 

in /etc/apache2/sites-available/000-default.conf

The fact is that
1). when I access http://...com/ that routed me to Login page
2). After I clicked a link

<Link to="main"><button>Log In</button></Link> 

the content in the browser location field become:

http://...com/main 

3). Now if I reload this url (http://...com/main), I got

The requested URL /main was not found on this server 

My rounting in React:

    <Router history={browserHistory }>       <Route path="/" component={TopContainer}>           <IndexRoute component={Login} />           <Route path='main' component={MainContainer} />          </Route> </Router> 

What else I am missing in the apache configuration?

thanks

like image 726
Mark Qian Avatar asked May 18 '17 04:05

Mark Qian


People also ask

Can Apache server run React?

In fact, it's entirely possible to deploy and host a React app on an Apache webserver; it's even possible to do this on shared hosting.

How do I add htaccess file to React?

In order for the routes to work in your React app, you need to add a . htaccess file. In the public_html folder, at the same level as the build file contents, add a new file and name it . htaccess.


1 Answers

Change the VirtualHost configuration (typically found in /etc/httpd/conf.d\vhosts.conf) by adding the following Rewrite* lines:

<VirtualHost *:8080>   ServerName example.com   DocumentRoot /var/www/httpd/example.com    <Directory "/var/www/httpd/example.com">     ...      RewriteEngine on     # Don't rewrite files or directories     RewriteCond %{REQUEST_FILENAME} -f [OR]     RewriteCond %{REQUEST_FILENAME} -d     RewriteRule ^ - [L]     # Rewrite everything else to index.html to allow html5 state links     RewriteRule ^ index.html [L]   </Directory> </VirtualHost> 

This tells Apache to serve any files that exist, but if they don't exist, just serve /index.html rather than a 404: not found.

  • Apache Reference: Configuring Apache Virtual Hosts

  • react-router History Reference: Configuring Your Server

Complete answer gratefully stolen from here

like image 178
Hinrich Avatar answered Sep 29 '22 20:09

Hinrich