0

I've built a React app to run on a single page of a WordPress site (http://example.com/myapp/). I'm using react-router. It works great with hashHistory, but I want to use the clean URLs that browserHistory offers.

I'm writing mod_rewrite and SetEnvIf recipes to solve the problem, but there is a strange complication with the WordPress rewrite rule. When I set REQUEST_URI, PHP winds up seeing that setting in REDIRECT_REQUEST_URI, which of course isn't where WordPress looks.

How can I set up the Apache side of a react-router app on a WordPress page?

Background: When setting environment variables in Apache RewriteRule directives, what causes the variable name to be prefixed with "REDIRECT_"?

Community
  • 1
  • 1
rep
  • 1,546
  • 1
  • 12
  • 19

1 Answers1

1

I tried lots of things to make this work without touching WordPress, but finally I gave up and entered a well-commented patch into my WordPress /index.php.

.htaccess:

# BEGIN myapp 
#  
# Set the REQUEST_URI to just /myapp for any deeper URI for the myapp React router. 
# 
# Unfortunately, this winds up setting REDIRECT_REQUEST_URI rather than 
# REQUEST_URI. See /index.php for a custom patch that works around this. 
# 
# Issue documented here: http://stackoverflow.com/a/10128290/1426950 
SetEnvIf Request_URI "myapp/.*" REQUEST_URI=/myapp/ 
# END myapp

/index.php:

/**
 *
 * CUSTOM PATCH
 *
 * Work around an Apache issue documented here: http://stackoverflow.com/a/10128290/1426950
 * We need it for the React app at /myapp/.
 *
 * We need the WordPress page at /myapp/ to be served for any URL beginning
 * with /myapp/, so that we can control that namespace with React. To
 * accomplish this, we set REQUEST_URI in the .htaccess, but a subsequent rewrite
 * pushes that setting over to REDIRECT_REQUEST_URI and resets REQUEST_URI.
 *
 * This PHP code fools WordPress into thinking Apache did what we wanted.
 *
 */
if (
  $_SERVER['REDIRECT_REQUEST_URI'] !== null
) {
  $_SERVER['REQUEST_URI'] = $_SERVER['REDIRECT_REQUEST_URI'];
}

Now everything works perfectly and WordPress serves the page at /myapp/ for all URLs of the React app (/myapp/foo, myapp/bar/123, etc.).

rep
  • 1,546
  • 1
  • 12
  • 19