且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

htaccess-使用PHP GET变量重写和重定向URL

更新时间:2023-11-26 23:41:34

请澄清一下,大概您已经将所有内部URL更改为/stocks-video-lessons 形式,并说明了原因外部重定向是因为丑陋的" URL已经被索引并在外部链接了?

Just to clarify, presumably you have already changed all your internal URLs to the form /stocks-video-lessons and the reason for the external redirect is because the "ugly" URLs have already been indexed and linked externally?

您已经发现,由于这两个规则相互冲突,并且不断地从一个重定向到另一个,因此您将获得重定向循环.

As you have found, you are getting a redirect loop because these two rules conflict and it's constantly redirecting/rewriting from one to the other.

仅在初始请求包含URL /video-lessons-page.php 而不是重写的URL时,您需要 redirect 这就是这里发生的事情).您可以通过检查 THE_REQUEST 服务器变量(包含浏览器发送的完整HTTP请求)来检查初始请求.

You need to redirect when only the initial request contains the URL /video-lessons-page.php, not the rewritten URL (which is what's happening here). You can check the initial request by checking against THE_REQUEST server variable (which contains the full HTTP request as sent by the browser).

类似以下内容:

RewriteCond %{THE_REQUEST} /video-lessons-page\.php?item=(\w+)
RewriteRule ^video-lessons-page\.php$ https://www.example.com/%1-video-lessons? [R=301,L]

RewriteRule ^(stocks|finance|accounting)-video-lessons$ video-lessons-page.php?item=$1 [L]

请注意,在进行测试之前,您必须清除浏览器缓存,因为301(永久)重定向将被浏览器缓存.(通常更容易使用302重定向进行测试.)如果您特别需要 不区分大小写的匹配项,则仅使用 NC 标志.

Note you must clear your browser cache before testing, since 301 (permanent) redirects will be cached by the browser. (Often easier to test with 302 redirects.) Only use the NC flag if you specifically need a case-insensitive match.

更新:我已将查询字符串参数值的正则表达式从( [^&] + )更改为限制性更强的(\ w + ). \ w 是单词字符的简写字符类(自然会排除& 并严格排除空格).由于 THE_REQUEST 包含以下形式的字符串:

UPDATE: I've changed the regex on the query string parameter value, from ([^&]+) to the slightly more restrictive (\w+). \w being the shorthand character class for a word character (which naturally excludes & and crucially spaces). Since THE_REQUEST contains a string of the form:

GET /video-lessons-page.php?item=stocks HTTP/1.1

...我们需要停止捕获之前的空间.先前的([[^&] +)模式将捕获到字符串末尾的所有内容,即.股票HTTP/1.1".因此,我会期望 404,因为将发生无效的重定向,但内部重写将失败.(?)

...we need to stop capturing before the space. The previous pattern ([^&]+) would have captured everything to the end of the string ie. "stocks HTTP/1.1". So, I would have expected a 404, since an invalid redirect would have occurred but the internal rewrite would have failed. (?)