我已经构建了一个React应用程序,可以在WordPress网站(http://example.com/myapp/)的单个页面上运行。我正在使用react-router。它适用于hashHistory
,但我想使用browserHistory
提供的干净网址。
我正在编写mod_rewrite和SetEnvIf配方来解决问题,但是WordPress重写规则存在一个奇怪的复杂问题。当我设置REQUEST_URI
时,PHP会在REDIRECT_REQUEST_URI
中看到该设置,这当然不是WordPress所在的位置。
如何在WordPress页面上设置react-router应用程序的Apache端?
答案 0 :(得分:1)
我尝试了许多工作来完成这项工作,而没有触及WordPress,但最后我放弃了并在我的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'];
}
现在一切正常,WordPress为/myapp/
的网页提供React应用的所有网址(/myapp/foo
,myapp/bar/123
等)。