【问题标题】:rewrite condition does not work重写条件不起作用
【发布时间】:2014-01-06 17:28:57
【问题描述】:

在我的php-项目中,我有以下文件夹结构。

/ [root]
|-- ... [some other folders]
|-- util/            // containing js,css files; should be accessible for anyone.
|-- client/          
    |--data/         // contains files which can be uploaded by users
       |-- private/  // should only be accessible for logged in users
       |-- public/   // should be accessible for anyone.
|-- ... [some other folders]
|-- index.php

我想实现以下行为:

  1. 如果有人直接访问 util/ 中的任何内容,他应该只获得他所请求的内容,如果它不是目录的话。
  2. 如果有人想访问client/ 中的任何文件,它应该被重定向到index.php。 例如,有人输入 url www.test.com/client/data/private/test.jpg,服务器应该以 index.php?request1=client/data/private/test.jpg 获取请求。
  3. 其他所有内容都应重写为index.php?request2=$1

我无法按预期获得第 2 点功能。

我使用以下 .htaccess 文件来处理这个问题:

RewriteEngine On

# allow access to all files within util/  WORKS!!
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)(util)($|/) - [L]

# here i have problems.. how can i achieve, that access to folder client/ is rewritten to index.php?request1=$1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^client
RewriteRule ^(.*)$ index.php?request1=$1 [QSA,L]

# rewriting everything else   WORKS!!
RewriteRule ^(.+)$ index.php?request2=$1 [QSA,L]

我在这里做错了什么?

【问题讨论】:

  • /client/dir1/dir2 在没有请求特定 文件 的情况下会发生什么?应该将其重写为 index.php,还是应该不修改目录访问?
  • 这应该被 RewriteRule 3 捕获或抛出这些 http 错误 401、404 之一。但我更喜欢规则 3
  • 啊等一下——REQUEST_URI 在匹配为^/client 时可能应该有一个前导/,因为这就是标题的结构。这与RewriteRule 期望在目录上下文中匹配的方式形成对比。试一试,这可能就是你所需要的。其他一切在我看来都是正确的。
  • 那也没用...但是谢谢
  • 打开重写日志并开始调试,我猜。

标签: regex apache .htaccess mod-rewrite redirect


【解决方案1】:

试试这个代码:

RewriteEngine On

# allow access to all files within util/  WORKS!!
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^util($|/) - [L]

# here i have problems.. how can i achieve, that access to folder client/ is rewritten to index.php?request1=$1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^client(/.*|)$ index.php?request1=$1 [QSA,L]

# rewriting everything else WORKS!!
RewriteRule ^((?!index\.php).+)$ index.php?request2=$1 [QSA,L]

【讨论】:

  • RewriteRule: 无法编译正则表达式 '^((?!index\\.php.+)$'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多