htaccess redirect for existence of a specific URL variable

让人想犯罪 __ 提交于 2019-12-01 12:16:34

问题


I've been reading hard for a good few hours and still can't find what I need! Hopefully someone here can help.

What I want to achieve is to redirect a specific URL with a specific variable to another page, but not when there are other URL variables present.

eg.

  • index.php?option=com_user - this needs to be redirected to index.php
  • index.php?option=com_user&view=login - this must not be redirected
  • index.php?option=com_user&view=login&foo=bar - this must not be redirected

I've found lots of examples that test for the existence of a given variable, but I want to test for that variable and test that no other variables exist.

Can anyone help?

Thanks in advance.


回答1:


Arguably, if you'll only be doing an internal redirection, your script can just ignore that parameter if other parameters are not present. But, that wasn't what you asked, so let's see how this can be done with mod_rewrite.

If we just care about if there's anything else in the query string, we can simply check if option=com_user is the only thing there:

RewriteEngine On

RewriteCond %{QUERY_STRING} =option=com_user [NC]
RewriteRule index\.php index.php?

However, this would still allow /index.php?option=com_user&complete=nonsense to slip through, so if we wanted to be a little more restrictive, we could do something like this:

RewriteEngine On

# Check if the query string contains option=com_user
RewriteCond %{QUERY_STRING} (^|&)option=com_user(&|$)
# Check that all of these other parameters were not provided
RewriteCond %{QUERY_STRING} !(^|&)view=
RewriteCond %{QUERY_STRING} !(^|&)foo=
RewriteRule index\.php index.php?


来源:https://stackoverflow.com/questions/3558590/htaccess-redirect-for-existence-of-a-specific-url-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!