盛夏, 贪吃小蘑菇的大白菜. 飘忽不定的过活的style下半.

Posted
3 04月 2009 @ 10pm

Tagged
Coding

基于nginx的wpmu hack, 使得nginx代替php处理静态文件.

php处理静态文件让我很不舒服,
所以今天研究了N久如何绕开php来做静态文件的处理.

先选取了自己以为最简单的实现方法, 用squid做反向代理.
装上了squid 3.1, 发现网上的config教程都是2.6的, 完全不适用,
研究了manual后, 配好了反向代理,
接着, 尴尬的事情就发生了, 因为是本地做反向代理,
无疑通过nginx来进行proxy_pass的结果就是死循环…

nginx –[proxy_pass]–> squid –[http request]–> nginx –[proxy_pass]–> squid…

太糟糕了, 要解决这个问题只有通过实现两个server, 并且重写host来实现反向代理.
庞大的工程. -____-#

后来转向nginx的X-SendFile功能,
原理是捕捉到特定的X-Accel-Redirect头后,
通过实现一个内部的location, 来完成一个重定向.

不过事情没有这么简单, 现有栋力博客的重写规则是:
rewrite ^.*/files/(.*) /wp-content/blogs.php?file=$1;

而静态路径里也含有 /files/ , 所以会被同时重写, 最后返回一个500 Internal Error,
并且这个error是没法通过FireBug或者日志来trace的.
研究了下nginx的判断逻辑, 加了一条URL判断后终于搞定.

详细的步骤如下:

[1] 修改nginx.conf, 建立internal location, 我把这个用于静态文件访问的location定为/static/.
同时避免/static/被重写, 加上缓存控制和防盗链设置, 最后的配置如下:

if ($request_filename !~ /static/)
{
rewrite ^.*/files/(.*) /wp-content/blogs.php?file=$1;
# to avoid being rewritten
}

location /static/
{
internal;
root /path/to/wpmu/;
expires 30d;

valid_referers none blocked *.dormforce.net;
if ($invalid_referer)
{
return 403;
}
}

[2] 修改/wpmu/wp-content/blogs.php, 仅留下以下代码:

define( ‘SHORTINIT’, true ); // this prevents most of WP from being loaded

require_once( dirname( dirname( __FILE__) ) . ‘/wp-config.php’ ); // absolute includes are faster

if ( $current_blog->archived == ‘1′ || $current_blog->spam == ‘1′ || $current_blog->deleted == ‘1′ ) {

status_header( 404 );

die(’404 — File not found.’);

}

# modified by killkeeper to support nginx’s X-SendFile feature :)

$file = “/static/”. constant( ‘UPLOADS’ ) . str_replace( ‘..’, ”, $_GET[ 'file' ] );
header(”X-Accel-Redirect: “. $file);

[3] 以上的两个steps 保证了静态文件可以被nginx这个正确的处理, 同时为了避免有用户注册static这个path, 需要在wpmu的后台里设置下, 把static屏蔽掉.

完工 :)



1 Comment

Posted by

Warning: mysqli::mysqli() [function.mysqli-mysqli]: (HY000/2002): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in /srv/public_html/df/wpmu/wp-includes/comment-template.php on line 1376

Warning: mysqli::real_escape_string() [function.mysqli-real-escape-string]: Couldn't fetch mysqli in /srv/public_html/df/wpmu/wp-includes/comment-template.php on line 1377

Warning: mysqli::query() [function.mysqli-query]: Couldn't fetch mysqli in /srv/public_html/df/wpmu/wp-includes/comment-template.php on line 1379

Fatal error: Call to a member function fetch_row() on a non-object in /srv/public_html/df/wpmu/wp-includes/comment-template.php on line 1380