React routes and rewrite rules
-
Hello,
first of all I want to thank rockiger for this great plugin. It works like a charm without having to change the code of the react app or learning some new stuff.
However, I have an issue which I cannot solve. I embedded the following simple react app in my local wordpress server:import { Routes, Route, Link, BrowserRouter } from "react-router-dom"; function Home() { return <h1>Home</h1>; } function Page1() { return <h1>Page 1</h1>; } function Page2() { return <h1>Page 2</h1>; } function App() { return ( <BrowserRouter> <nav> <Link to="/page1">Page 1 </Link> <Link to="/page2">Page 2</Link> </nav> <Routes> <Route path="/" element={<Home />} /> <Route path="/page1" element={<Page1 />} /> <Route path="/page2" element={<Page2 />} /> </Routes> </BrowserRouter> ); } export default App;
I have chosen the string “test” as URL slug. But I don’t want to use the app via the urls “localhost/test” or “localhost/test/page1”. Instead they should be accessed via “localhost” or “localhost/page1”. So I added the following rewrite rule to my function.php file:
function rewrite_route() { add_rewrite_rule('^(.+)', 'index.php?pagename=test', 'top'); } add_action('init', 'rewrite_route');
This rule is intended to redirect a route like “localhost/page1” to the react app. Here comes the problem: In the wordpress dashboard at “Settings -> Reading -> Your homepage displays” there are two options available:
First Option: Your latest posts
With this option the routes “localhost/page1” and “localhost/page2” work as intended and show the pages from the react app. But of course the route “localhost” leads to page with the latest posts.Second option: A static page (with Homepage set to “test”)
With this option the route “localhost” works as intended and shows the root page page of the react app. But the routes “localhost/page1” and “localhost/page2” don’t work anymore, as they deliver the same page as the route “localhost”.So my question is the following: Is it possible with one of the two options enabled that the routes “localhost”, “localhost/page1” and “localhost/page2” show the content of my react app?
- The topic ‘React routes and rewrite rules’ is closed to new replies.