Mod重写除特定子文件夹以外的所有内容

时间:2015-06-25 07:18:32

标签: regex apache .htaccess mod-rewrite

我尝试将子文件夹adminapi以外的所有内容重定向到admin,所以:

/           - redirects to /admin
/some-url   - redirects to /admin
/admin      - doesn't redirect
/admin/1    - doesn't redirect
/api        - doesn't redirect
/api/v1/etc - doesn't redirect

但到目前为止我所做的并没有正确重定向。这是我的mod_rewrite:

<IfModule mod_rewrite.c>
  RewriteEngine on

  RewriteCond %{REQUEST_URI} !^/(admin|api)
  RewriteRule ^ /admin [R,L]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ ./index.php [L]

</IfModule>

1 个答案:

答案 0 :(得分:0)

您应该使用THE_REQUEST变量而不是REQUEST_URI,因为REQUEST_URI由于上一个规则而更改其值,然后在第一个规则中的mod_rewrite重写条件的下一次迭代中返回true

<IfModule mod_rewrite.c>
  RewriteEngine on

  RewriteCond %{THE_REQUEST} !/(admin|api) [NC]
  RewriteRule ^ /admin [R,L]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ ./index.php [L]

</IfModule>