我应该如何在.htaccess中使用<If>指令?

我试图在我的.htaccess文件中使用Apache的If指令添加一个条件语句。

我已经引用这个页面http://httpd.apache.org/docs/trunk/mod/core.html#if,但是它没有详细说明/给出很多例子。 两个不完整的例子是:

 <如果%{REQUEST_METHOD}进入GET,HEAD,OPTIONS> 

 <如果“$ req {Host} =''”> 

所以我试着把这个添加到我的.htaccess文件中:

 <如果%{SERVER_PORT}进入GET,HEAD,OPTIONS>
   这里还没有
 </如果>

但是当我尝试加载页面时,我总是收到错误500 。 这是我的本地安装,它以前工作正常(或如果我删除该代码)。 我相信我的AllowOverride All全局设置,If指令的上下文应该让它在.htaccess(“上下文:服务器configuration,虚拟主机,目录,.htaccess”)。

有人可以给我一些如何正确使用<If>指令的例子,或者为什么它不适合我的一些指导?

谢谢!

<If>指令仅在Apache 2.4及更高版本中可用。

http://httpd.apache.org/docs/2.4/mod/core.html#if

2.2中没有文档:

http://httpd.apache.org/docs/2.2/mod/core.html#if

<If>仅在Apache 2.4+中可用,所以首先确保你有这个版本。

例子

 # Compare the host name to example.com and redirect to www.example.com if it matches <If "%{HTTP_HOST} == 'example.com'"> Redirect permanent "/" "http://www.example.com/" </If> <If "%{HTTP_HOST} =~ /regex/"> SecFilterEngine Off SecFilterScanPOST Off </If> <If "%{REQUEST_URI} =~ m#/regex/including/slashes/#"> SecFilterEngine Off SecFilterScanPOST Off </If> 

替代<If>

如果您仍然坚持使用Apache 2.2,还有其他一些解决scheme可以用来做条件语句。

  • 你可以通过设置环境variables:

    • Apacheconfiguration
    • SetEnvIf
    • mod_rewrite的RewriteMatch
  • 然后你可以使用执行条件语句

     <IfDefine MyEnvironmentVar> ... </IfDefine> 

例:

 # Set environment variable if we're on staging site SetEnvIf Host staging ROBOTS_NOINDEX # Set environment variable if we're within a specific folder SetEnvIf Request_URI ^/app/webroot/files/ ROBOTS_NOINDEX # Send custom header if environment variable is set Header set X-Robots-Tag "noindex" ENV=ROBOTS_NOINDEX