apache rewrite 计算(使用apache的RewriteMap使用php自定义脚本)


查找相关文章:apache RewriteMap

本文参考 

http://www.ooso.net/archives/493

http://www.cnxct.com/apache-rewritemap-%E4%BD%BF%E7%94%A8%E6%89%8B%E8%AE%B0/

http://www.wellho.net/resources/ex.php4?item=a603/andy


我希望实现的功能是

http://www.dayanmei.com/test/987651/

页面实际上write到一个md5散列文件(987651的md5值是91eea237ce40770a4b27c7bdef38d2fb)

http://www.dayanmei.com/cache/91/ee/91eea237ce40770a4b27c7bdef38d2fb.htm

这样可以使用真正的静态文件,又不至于单个文件夹下面放置太多的文件而影响系统性能

<VirtualHost *:80>
  # General
  ServerAdmin admin@dayanmei.com
  DocumentRoot /var/www/html/dayanmei.com
  ServerName dayanmei.com
  ServerAlias www.dayanmei.com
  # Logging
  ErrorLog logs/dayanmei-error_log
  CustomLog logs/dayanmei-access_log common


RewriteEngine On
RewriteMap file_hash prg:/var/www/html/dayanmei.com/test/file_hash.php
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
RewriteRule ^/test/(.*)$ ${file_hash:$1|0} [L]

</VirtualHost>


查看错误日志,发现

(13)Permission denied: mod_rewrite: could not start RewriteMap program /var/www/html/dayanmei.com/test/file_hash.php

Configuration Failed

给file_hash.php文件加上可执行权限

chmod +x var/www/html/dayanmei.com/test/file_hash.php

file_hash.php文件内容

#!/usr/bin/php -f
<?php
error_reporting(0);

function file_hash($str){
        $mstr = md5($str);
        return '/cache/'.substr($mstr,0,2).'/'.substr($mstr,2,2).'/'.$mstr.'.htm';
}

while($in = trim(fgets(STDIN))){
        fputs(STDOUT, file_hash($in)."\n");
}
?>

apache 的error.log中会记录<strong>[warn] mod_rewrite: Running external rewrite maps without defining a RewriteLock is DANGEROUS!</strong>这样的错误日志,在httpd.conf中添加RewriteLock /tmp/rewrite.lock,就不会报错了