【问题标题】:htaccess query_string redirect only when string equals a specific valuehtaccess query_string 仅在字符串等于特定值时重定向
【发布时间】:2012-01-24 19:04:23
【问题描述】:

我一直在寻找如何做到这一点的几个小时,感觉好像我很接近了。

我正在尝试根据 URL 中传递的字符串参数将特定访问者重定向到我网站上的不同页面。

例如,我希望将 URL mysite.com/index.php?src=msn&test=1 重定向到 mysite.com/msn/index.php?src=msn&test=1

我打算让我的普通网站访问者访问 index.php 页面而不被重定向,所以它应该只在查询字符串与我设置的值匹配时重定向。

这是我的代码:

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{QUERY_STRING} ^src=msn(.*)$
RewriteRule ^(.*)$ http://www.mysite.com/msn/ [L]

当我转到 URL mysite.com/?src=msn&test=1 时,上面的代码有效,但它不适用于 mysite.com/index.php?src=msn&test=1。知道当我输入 index.php 时如何让它工作吗?

谢谢。

编辑:::

我的 .htaccess 文件中也有以下规则:

 ErrorDocument 404 /error404.php

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

 RewriteEngine on
 RewriteCond %{HTTP_HOST} ^mywebsite\.com$ [NC]
 RewriteRule ^(.*)$ http://www.mywebsite.com/$1 [R=301,L]

第一个是404重定向,第二个是wordpress文件更改,最后一个强制所有页面为http://www

【问题讨论】:

  • 你的htaccess中还有其他规则吗?
  • Ulrich,我已经更新了原始帖子以在 .htaccess 文件中显示其他规则。

标签: .htaccess


【解决方案1】:

这一行

重写规则 ^index.php$ - [L]

防止 index.php 进一步处理。

最简单的解决方案是将新规则移到顶部,如下所示(我假设它们都在同一个 .htaccess 文件中)

ErrorDocument 404 /error404.php

Options +FollowSymlinks
RewriteEngine on
RewriteBase /blog/

#rule to add www to domain
RewriteCond %{HTTP_HOST} ^mywebsite\.com$ [NC]
RewriteRule ^(.*)$ http://www.mywebsite.com/$1 [R=301,L]

#new rule to redirect based on query string param
RewriteCond %{QUERY_STRING} ^src=msn(.*)$
#unless it is already msn
RewriteCond %{REQUEST_URI} !^/msn/ [NC]
RewriteRule ^(.*)$ http://www.mysite.com/msn/ [L,R]

#rules for blogs
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]

【讨论】:

  • 谢谢,现在说得通了。对于我对 .htaccess 的基本理解,我深表歉意,但我现在遇到的问题是我无法阻止规则应用于我要重定向的页面,因此我进入了无限循环。知道如何解决这个问题吗?
  • @user1167727 添加了一个额外的条件来防止上述情况发生
猜你喜欢
  • 1970-01-01
  • 2015-02-09
  • 1970-01-01
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 2015-03-31
相关资源
最近更新 更多