从 React 页面重定向到 WordPress 实例

问题描述 投票:0回答:1

我在

https://example.com/
上有一个 React 应用程序,里面有一个 WordPress 博客作为子目录:
https://example.com/blog/

问题: 浏览

https://example.com/blog
时,我希望将其重定向 (301) 至
https://example.com/blog/
但目前它显示错误 404,因为它将
https://example.com/blog
视为反应页面。

这是我的根

.htaccess
:

# Disable directory indexes and MultiViews
Options -Indexes -MultiViews

# Prevent mod_dir appending a slash to directory requests
DirectorySlash Off

RewriteEngine On

# Prevent any further processing if the URL already ends with a file extension
RewriteRule \.\w{2,4}$ - [L]

# Redirect any requests to remove a trailing slash
RewriteRule (.*)/$ /$1 [R=301,L]

# Rewrite /foo to /foo.html if it exists
RewriteCond %{DOCUMENT_ROOT}/$1.html -f
RewriteRule (.*) $1.html [L]

# Otherwise, rewrite /foo to /foo/index.html if it exists
RewriteCond %{DOCUMENT_ROOT}/$1/index.html -f
RewriteRule (.*) $1/index.html [L]

这是我的 WordPress

.htaccess
:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]

RewriteCond %{REQUEST_URI} /+[^\.]+$
    RewriteCond %{REQUEST_URI} !^/wp-json
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

</IfModule>

我该怎么做才能将

https://example.com/blog
重定向到
https://example.com/blog/
?应该是301重定向。

我尝试将规则添加到两个实例的

.htaccess
。但两者都不起作用。

reactjs wordpress .htaccess mod-rewrite mod-dir
1个回答
0
投票
# Prevent mod_dir appending a slash to directory requests
DirectorySlash Off

DirectorySlash Off

 文件中的 
.htaccess
 指令将阻止 Apache (mod_dir) 通过 301 重定向将尾部斜杠附加到 
/blog
 子目录。 (通常,当物理文件系统目录中省略 mod_dir 时,mod_dir 会“自动”在尾部斜杠后面附加 301 重定向。
DirectorySlash On
 是默认值。)

但是,您不能简单地删除此指令,因为您将无条件地从该文件后面的所有请求中删除尾部斜杠。 (我猜这是你的 React 应用程序的

要求?)

RewriteCond %{REQUEST_URI} /+[^\.]+$ RewriteCond %{REQUEST_URI} !^/wp-json RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

您正在

/blog/.htaccess文件中的请求中追加

尾随斜杠,尽管这对于覆盖
/blog
目录本身来说已经太晚了。这条规则可能是在错误的地方,尽管这确实取决于意图是什么(并且无论如何与这个问题没有直接关系)。

解决方案

为了维护 React 应用程序中的无斜线目录(如果这是意图?),那么您需要向根

.htaccess

 文件添加几个附加指令(紧接在 
RewriteEngine
 指令之后)明确地将尾部斜杠附加到 
/blog

例如:

# Allow mod_rewrite to match slash-less directory (Apache 2.4+) RewriteOptions AllowNoSlash # Redirect "/blog" to "/blog/" RewriteRule ^blog$ /$0/ [R=301,L]
其中 

$0

 是包含 
RewriteRule
 
模式的完整匹配的反向引用。

一旦发生重定向,

/blog/.htaccess

文件就会被触发并有效地覆盖根
.htaccess
文件。

旁白:你的问题有点不清楚,但看起来你已经手动编辑了WordPress代码块内的代码(在# BEGIN WordPress

/
# END WordPress
注释标记之间) - 不建议这样做。 (除非您阻止 WP 修改 
.htaccess
 文件。)

© www.soinside.com 2019 - 2024. All rights reserved.