【问题标题】:htaccess: condition to check if string is in requesthtaccess:检查字符串是否在请求中的条件
【发布时间】:2017-02-11 11:24:39
【问题描述】:

我需要为 mod rewrite URL 规则编写条件以检测正在执行的页面。

我使用的RewriteRule 工作正常,但问题是我需要对两个不同的 URL 使用相同的规则。

RewriteRule ^testing/([^/]*)$ /index.php?url=$1&name=&submit=submit [NC,L] 
RewriteRule ^testing/([^/]*)$ /test.php?url=$1&name=&submit=submit [NC,L]

在没有设置任何重写条件的情况下,在浏览器中添加example.com/testing/ 时,无论我是在index.php 还是test.php,都会使用htaccess 中的第一个RewriteRule

这是我尝试过的一些RewriteCond
RewriteCond %{REQUEST_FILENAME} /test.php$
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ (test\.php)/ [NC]
RewriteCond %{THE_REQUEST} \s/+(test\.php)/ [NC]
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /test\.php/

这是完整的 htaccess 文件代码:

Options +FollowSymLinks
RewriteEngine on
## check if on index.php ##
RewriteCond %{THE_REQUEST} ^.*\/index.php\/.*$ ## not working ##
## if on index.php do this ##
RewriteRule ^testing/([^/]*)$ /index.php?url=$1&name=&submit=submit [NC,L]  
## check if on test.php ##
RewriteCond %{THE_REQUEST} ^.*\/test.php\/.*$ ## not working ##
## If on test.php do this ##
RewriteRule ^testing/([^/]*)$ /test.php?url=$1&name=&submit=submit [NC,L]

如何让第一个 (index.php) rewriteRuleindex.php 上工作,但在 test.php 页面上时忽略第一个规则并使用第二个?

谢谢:)

编辑:只是为了澄清。我不想重定向。我只想根据我所在的页面更改testing/ 的值。正如我提到的 rewriteRule 已经可以正常工作了。

【问题讨论】:

  • 你不能那样做。通过您的链接/testing/...,无法知道它是针对index.php 还是针对test.php。您可以使用代码或名称更改链接,例如testingitestingt,或testing/i...等。
  • 这就是条件应该是什么。这个想法是如果index.php 在脚本名称中,则执行规则,如果没有则不执行。如果test.php 在脚本名称中,则执行该规则。如果没有,那就不要。
  • %{HTTP_REFERER} 网址中?因为你重写了你的链接,当你使用它时,不是脚本名...
  • 不,我不想重写脚本名称。我想测试脚本名称是否包含字符串。如果是,则重写 URL。
  • 你不懂... Apache 会在你使用时重写你的链接。不是在您运行脚本时。当用户单击链接时,您有时可能会在%{HTTP_REFERER} 中读取脚本名称(对不起,我的英语不好)

标签: php apache .htaccess mod-rewrite url-rewriting


【解决方案1】:
## If on index.php ##
RewriteRule    "^/index\.php$"  "/index.php?url=$1&name=&submit=submit" [R,L]

试试这个

【讨论】:

  • 对不起@Elby 我想你可能误解了一点。该规则工作正常。 mod 重写后的 URL 如下所示:example.com/testing/youtube.com(youtube.com 只是一个示例)
【解决方案2】:
RewriteEngine On

#Checking if /index.php/ apears in URI
RewriteCond %{REQUEST_URI} ^(.*)\/index\.php\/(.*)$ [NC]
RewriteRule ^(.*)$ testing/index.php?url=$1&name=&submit=submit [NC]

这将显示 index.php?url=sth1/index.php/sth2 输出而不是 sth1/index.php/sth2

祝你好运

【讨论】:

  • 我不想重定向。我需要根据我所在的页面更改testing/ 的值。
  • @turrican_34,你能举例说明一下吗?
  • 我已经更新了完整 htaccess 代码中的 cmets。你不明白哪一部分?
  • @turrican_34,用户的具体要求是什么,你想显示哪个文件?
  • 正如我所提到的,我基本上需要更改testing/ 的值。如果 index.php 在脚本名称/请求(条件)中,则使用 rewriteRule:RewriteRule ^testing/([^/]*)$ /index.php?url=$1&name=&submit=submit [NC,L] 。如果test.php 在脚本名称/请求(条件)中,则使用 rewriteRule:'RewriteRule ^testing/([^/]*)$ /test.php?url=$1&name=&submit=submit [NC,L] '。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-05
  • 2015-12-07
  • 2019-02-27
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多