Make a PHP homepage for your React App using Rewrite Rules

Posted by N.G. Onike on February 15, 2021 Software Technology Web Development

You may be thinking ? Why React with PHP and how does Shared Hosting, CPanel and NGinx/Apache come into play ?

Well, I possess shared hosting which is managed via an Admin Interface known as CPanel. This shared hosting houses some of my applications. When I made the decision to redesign some of my pages/services while learning React, especially as I got comfortable around the technology, I wasn't ready to move all hosting services to the cloud or otherwise even though this would have been an ideal and the trendy approach.

Also, it would have been pointless shifting several running services because of a few Webpages in this case. I'd rather build out new services on the cloud and migrate the old over time. This is also because i'm quite familiar with PHP servers and still comfortable around it. Continuing to use my shared hosting also saved costs.

Note that I do have services on the cloud. Also note that a lot of traditional hosting companies have moved some of their services on the cloud to take advantage of its benefits.

This is not for a comparison between services but rather for a suitable work around mixing both.                                                                          

Now, I'd decided to see how i can make these different technologies(ReactJS, PHP, CPanel) work together.

My options for doing that included the following approaches:

  • Calling React using JavaScripts <script> tag

This option allows me to sprinkle React in an existing application by calling it via JavaScripts' tag only on the pages where I require React. It can be integrated into any technology that can handle JavaScript.

Pros: This is a very lightweight approach as it doesn't ship with all the weight/baggage that comes with the full React setup.

Cons: If you have to ever expand Reacts functionalities within your app, you will spend time having to keep adding modules( which would have been in a full React setup ) to support your project.

  • Using the Create React App  method only

You may be familiar with the command above which creates a scaffold for a react App. This is the official out-of-the-box setup and ships with the basic dependencies you will need. It can be packaged and served via varying servers. Usually its backend service is handled with NodeJS and Express and runs mostly on the cloud.

Pros: You don't have to keep installing dependencies and it possesses all the basic things you need to run a fully optimised React App.

Cons: It can ship with the full package so it can get bulky. You probably will have dependencies you may never use. This method is also optimised specially for React so attaching disparate technologies may be a hassle.

  • Decoupled Approach

Here, I split up the functionalities I want for only my React App such a building only the user interface(UI) layer in React, calling React only where necessary, minimising the app with React's Build command and running a different/separate backend service. Essentially a mix.

Pros: Lightweight since I only make use of React where necessary. Easier to slowly implement/increase Reacts functionality across an existing system as one can add pages/services at ones own pace. Easier to integrate other existing programmers and technologies.

Cons: Most suitable for programmers skilled across technologies as well as a steep learning curve getting dissimilar technologies to work together. 

As you may bet, I had to go for the 3rd option. Decoupled Approach.

Decoupled

It may interest you to know that my portfolio web application is decoupled with its blogs service as a headless CMS running on Rails in the cloud, PHP for some front and backend services and React for other parts of my UI. They're all linked together with Https.

Hopefully, there'd be an article dedicated to the full intricacies of that journey.

That article is not this article.

However, this piece engages the tail-end aspects of implementing a decoupled service using the specified technologies and focuses on the Key to combining these different technologies which is where it matters most.

System Design

I went about building just the pages i needed for my react app. In my portfolio case, that was my: About, Projects and Contact Pages. 

I left my homepage under PHPs service thereby keeping my entry/index/main page well connected to the rest of my existing services on the shared host.

A majority of my backend also remained firmly in PHP and CPanel's grasp.

                           undefined

Build

Since my homepage already existed in PHP, I had to design the UI and frontend for just my React pages.

I used the Create a React App method for this so as to enable me have access to all node functionalities. I then built the pages accordingly.

When you are sure your react app pages are set and ready for deployment, you should go to your package.json  file in your project folder's root and change your homepage accordingly.

I'm assuming here that you already have a custom domain for your application. Use this domain path for your homepage.

See sample below. 

  "homepage": "https://mywebsite.com",

For deployment, having certified that all my files are set, I use the React Build command to prepare those pages for production. See the command below.

npm run build

This command will create a build folder of my static site but minimised and optimised only with the necessary dependencies thereby reducing app size.

After running this command, my React Applications files packaged in a build folder should look as below

                                 

This build folder houses your static entry page index.html  . Servers like Nginx, Apache or Node (express) can be used to serve your project.

In our case, Nginx will handle our sites server but my hosting provider itself is powered mostly by Apache. Yes, you can mix both technologies.

Serving and Deployment

In serving our project, we copy all the files in our Build folder to our projects root  public_html folder.

Note that we copy only the file contents and not the Build folder itself.

We can achieve this using a File Transfer Protocol ( FTP ) or Secure FTP ( SFTP ) or just upload the files via CPanel using the traditional upload approach.

Note that we already have an existing index.php homepage in our root folder.

What your public_html file for a samplesite should look like below.

                                 

It is likely that our server will naturally redirect homepage requests to index.html since that file trumps the index.php file or other files formats as well as us, having earlier specified the homepage in our package.json file in our React app.

This, we do not want. So we proceed to change that below.

ReWrite Modules

This is the Key to our aim. So pay close attention here.

Rewrite modules or rules change part or all of the URL in a client request. This is to inform the client of a files location or to control the flow process for file path requests.

The rewrite module rules are placed in a file in our projects root i.e public_html .

This file is simply named .htaccess

.htaccess file is a powerful website file that controls high-level configuration of your website. On servers that run Apache and Nginx, the .htaccess file allows you to make changes to your website's configuration without having to edit server configuration files.

This file will also resides at the very top, at our projects root folder.

If we were to make our react app as the homepage, we would simply paste the code below which tells our server to serve Reacts index.html static file as our homepage.

Note that the .htaccess code below is sufficient to serve your React app straightaway on the server.

See below. 

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]

</IfModule>

However,

this is not just what we want.

We already have a homepage which is in PHP. We do not want our React entry page as our homepage.

We want our already existing index.php file to serve as our homepage.

To achieve this, we add some extra rules( dir_module ) to the top of our .htaccess file.

Take note of the file content and where we place the index.php within the code.

These rules identify the Directory's index. The first specifying the homepage and the second indicates the alternative homepage for our Reacts app.

They also specify the file types and the Rewrite conditions. An in-depth review of these codes are beyond our scope.  

See below.

<IfModule dir_module>
 
   DirectoryIndex index.php index.html
   RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
   RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]

</IfModule>

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]

</IfModule>

Voila! Save the file and visit your homepage in your favorite browser. Your index.php should appear as your homepage if you did it right. You can link that page to your static site with Https.

Take Home

The rules specified in the code above will redirect the homepage of our application to the Directory Index first specified within the code.

The second rules in the same file enable the react app to be served and to work appropriately via our server.

We can also use the ReWrite modules to specify Error page redirects ( 404 ) or other such network protocols. 

QUICK-SHARE :