如何使用.htaccess设置条件DirectoryIndex

时间:2014-07-14 13:19:47

标签: apache .htaccess mod-rewrite redirect

我想尝试布局,看看哪些有效,哪些无效。如果某些事情不起作用,我不想对所有流量做到这一点。为此,我想将部分流量重定向到单独的文件。我想用.htaccess这样做。我的第一次尝试是重定向具有以1或2结尾的IP地址的人来获得新布局。我想动态设置DirectoryIndex来执行此操作。

这就是我所拥有的:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /

#split 20% of the traffic to go to the alternative layout
RewriteCond %{REMOTE_ADDR} "*(1|2)$"
RewriteRule .? - [S=4]
RewriteRule ^fb/([^/]+) /fb.php?id=$1 [nc]
RewriteRule ^classic /?layout=classic [QSA,nc]
RewriteRule ^thumbs /?layout=thumbs [QSA,nc]
DirectoryIndex 3.php

#the rest of the traffic goes to the default layout
RewriteCond %{REMOTE_ADDR} "!(1|2)$"
RewriteRule .? - [S=1]
DirectoryIndex index.php index.html

AddDefaultCharset utf-8

虽然这并没有达到预期的效果,但如果我能在.htaccess中使用这个伪代码,我会很激动:

if %{REMOTE_ADDR} matches "*(1|2)$"
   DirectoryIndex 3.php
else
   DirectoryIndex index.php

1 个答案:

答案 0 :(得分:1)

直接翻译此块

if %{REMOTE_ADDR} matches "*(1|2)$"
   DirectoryIndex 3.php
else
   DirectoryIndex index.php

我们可以使用mod_rewrite这样的规则:

# default value of DirectoryIndex
DirectoryIndex index.php

RewriteEngine On

# use 3.php instead if following condition is true
RewriteCond %{REMOTE_ADDR} (1|2)$
RewriteRule ^(.+?/)?index\.php$ $13.php [L,NC]