如果 url 不包含子字符串,如何将路径添加到 url

How add path to url if the url does not contain substring

我需要重定向来自 https://example.com/*https://example.com/test/* 如果 URL 不包含 test 子字符串。

到目前为止我有这些重写规则

RewriteBase /

RewriteCond %{THE_REQUEST} !^/test
RewriteRule ^/?$ /test/ [R=301,L] # if the url does not contain test, redirect to url with test

RewriteCond %{THE_REQUEST}% test
RewriteRule ^test?(.*)$ / [L] # mask the fact that the url is not https://example.com/ and instead is https://example.com/test but apache serve the website like if it was on root

如果我访问 https://example.com 它会重定向到 https://example.com/test 但由于第二条规则会出现无限循环。

我如何组合它,所以对 https://example.com/test* 的请求不会被重定向,但是 https://example.com/* 的那些请求不需要更改 www 根目录,所以它适用于所有 [=28] =]s.

更新:

The test should be in url (for user experience), but the apache should route like if it was not in url and instead the request came to root url, so application routing is preserved internally without having to change the app itself.

啊,好的。但是,您应该链接到应用程序中的 /test URLs(因此尽管您最后发表评论,您仍然需要“更改应用程序”),否则 /test 不是实际上在用户和搜索引擎在页面上看到的 URL 中(它们将被 重定向 )并且您的用户每次单击您的链接之一时都会遇到外部重定向(不利于 SEO 和用户体验)。

.htaccess 中实现的“重定向”以 /test 为“旧”URL 前缀仅用于 SEO - 与任何“旧”到“新”一样 URL改变。 (您的应用运行不需要它 - URL-path 中的 /test - 因为您的内部 URL 应该已经包含 /test。)

试试这样:

RewriteEngine On

# Insert "/test" at the start of the URL-path if absent in "direct" requests
RewriteRule %{ENV:REDIRECT_STATUS} ^$
RewriteRule !^test/ /test/ [R=301,L]

# Rewrite "/test" URLs back to root
RewriteRule ^test(?:$|/(.*)) / [L]

REDIRECT_STATUS 环境变量用于防止重定向循环。这在客户端的初始请求中为空,并设置为重写后的 HTTP 响应状态(如下)。

首先使用 302(临时)重定向进行测试,只有在您确定它按预期工作时才更改为 301(永久)。

测试前您需要清除浏览器缓存。