如果 URL 不包含子字符串,我需要将所有请求重定向https://example.com/*
到。https://example.com/test/*
test
到目前为止,我有这些重写规则
RewriteBase /
RewriteCond %{THE_REQUEST} !^/test
RewriteRule ^/?$ /test/$1 [R=301,L] # if the url does not contain test, redirect to url with test
RewriteCond %{THE_REQUEST}% test
RewriteRule ^test?(.*)$ /$1 [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 根目录,因此它适用于所有 URL。
更新:
测试应该在 url 中(为了用户体验),但是 apache 应该像不在 url 中一样路由,而是请求到达根 url,因此应用程序路由在内部保留,而无需更改应用程序本身。
喔好吧。但是,您应该链接到/test
您的应用程序中的 URL(因此您仍然需要“更改应用程序”,尽管您最后发表了评论),否则/test
实际上不在用户和搜索引擎在页面上看到的 URL 中(他们将被重定向),并且您的用户每次单击您的链接之一时都会体验到外部重定向(对 SEO 和用户体验不利)。
.htaccess
为“旧” URL 添加前缀的“重定向”/test
仅用于 SEO - 与任何“旧”到“新” URL 更改一样。(您的应用程序不需要/test
在 URL 路径中运行 - 因为您的内部 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/$1 [R=301,L]
# Rewrite "/test" URLs back to root
RewriteRule ^test(?:$|/(.*)) /$1 [L]
REDIRECT_STATUS
环境变量用于防止重定向循环。这在来自客户端的初始请求中为空,并在重写后设置为 HTTP 响应状态(如下)。
首先使用 302(临时)重定向进行测试,只有在您确定它按预期工作时才更改为 301(永久)。
您需要在测试前清除浏览器缓存。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句