有条件的RewriteBase

时间:2015-10-22 12:31:49

标签: apache .htaccess mod-rewrite

我将Apache 2.4与mod_rewrite一起使用,我遇到了无法解决的问题。

我有一个包含

.htaccess文件
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    ... RewriteRules ...
</IfModule>

这很好用。现在我需要执行以下操作:如果有人以http://my.web.page.com访问我的网站,我需要RewriteBase /,如上例所示。但如果有人以http://192.168.1.10/xyz访问该网站,我需要RewriteBase /xyz

我想我可以使用<If expression>...</If>来实现这一目标,但我无法正确编写表达式。

xyz是固定字符串。它不必从URL复制,但可以在RewriteBase /xyz命令中进行硬编码。

我该怎么做?

修改

@anubhava提出了一个表达方式,我无法开始工作。所以我尝试了一些非常简单的<If...>语句,只使用RewriteBase /语句。

我现在非常非常困惑。

尝试1

RewriteEngine On
RewriteBase /

<If "false">
  RewriteBase /
</If>

这很有效。到现在为止还挺好。现在让我们启用条件:

尝试2

RewriteEngine On
RewriteBase /

<If "true">
  RewriteBase /
</If>

这不起作用。因此启用条件会产生影响。也许这两个RewriteBase语句会导致代码失败。

尝试3

RewriteEngine On

<If "true">
  RewriteBase /
</If>

不,这仍然不起作用。也许只是存在条件才是问题?

尝试4

RewriteEngine On
RewriteBase /

<If "true">
  #RewriteBase /
</If>

这很有效。所以条件本身是无害的。我不能在其中写RewriteBase

为了完整起见,我使用的重写规则是:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

Apache错误日志不包含错误信息。

第二次编辑

根据@anubhava的建议,我设法让这个工作:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# case 1
RewriteCond %{HTTP_HOST} =my.web.page.com
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

# case 2
RewriteCond %{HTTP_HOST} ^192\.168\.
RewriteRule ^(.*)$ xyz/index.php?/$1 [L,QSA]

1 个答案:

答案 0 :(得分:2)

根据您编辑的问题,这些规则应该有效:

RewriteEngine On 
RewriteBase /

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# case 1
RewriteCond %{HTTP_HOST} =my.web.page.com
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

# case 2
RewriteCond %{HTTP_HOST} ^192\.168\.
RewriteRule ^(.*)$ xyz/index.php?/$1 [L,QSA]