刚开始从Apache转向Nginx是一个痛苦的过程,经过一段时间的折腾,现在总算解决了不少问题,使得VPS能正常工作了,写上篇博文时博客已经开始在Xen的VPS上运行了。
推荐的一个Apache .htaccess转换成Nginx rewrite的网站:点这里,还需要用到一些Nginx的语知识:点这里。
这里简单摘录一些Nginx的语法,方便使用:
文件及目录匹配 -f和!-f 用来判断是否存在文件 -d和!-d 用来判断是否存在目录 -e和!-e 用来判断是否存在文件或目录 -x和!-x 用来判断文件是否可执行 正则表达式匹配 ~ 为区分大小写匹配 ~* 为不区分大小写匹配 !~ 为区分大小写不匹配 !~* 为不区分大小写不匹配 Nginx Rewrite 基本标记(flags) last 相当于Apache里的[L]标记,表示完成rewrite,不再匹配后面的规则 break 中止Rewirte,不再继续匹配 redirect 返回302临时重定向,地址栏会显示跳转后的地址 permanent 返回301永久重定向,地址栏会显示跳转后的地址 Nginx 的一些可用的全局变量,可用做条件判断 $args $content_length $content_type $document_root $document_uri $host $http_user_agent $http_cookie $limit_rate $request_body_file $request_method $remote_addr $remote_port $remote_user $request_filename $request_uri $query_string $scheme $server_protocol $server_addr $server_name $server_port $uri
有了这些知识我们就可以动手把奶瓶退迁移了,首先找到其根目录和oauthproxy子目录下的.htaccess,分别用上面提到的网站把他们转成Nginx格式的,比如根目录的原内容:
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
转换后得到这个结果:
if (!-f $request_filename){ set $rule_0 1$rule_0; } if (!-d $request_filename){ set $rule_0 2$rule_0; } if ($rule_0 = "21"){ rewrite ^/(.*)$ /index.php?q=$1 last; }
通过前面Nginx的语法知识得知可以把前两个!-f和!-d合并成!-e,清减后:
if (!-e $request_filename){ rewrite ^/(.*)$ /index.php?q=$1 last; }
接下来需要解决的问题时子目录的处理,假设我们把奶瓶腿建在/tw/nt子目录下(加子目录越深越不容易被扫到),这样location的写法就成了:
location /tw/nt { if (!-e $request_filename){ rewrite ^/tw/nt/(.*)$ /tw/nt/index.php?q=$1 last; } }
oauthproxy子目录以此类推得到这个location:
location /tw/nt/oauthproxy { if (!-e $request_filename) { rewrite . /tw/nt/oauthproxy/index.php last; } }
因为这里转向的目标不需要参数,所以判断条件直接用“.”表示任意匹配。 其它以此类推,但需要注意的是这些需要放在“location ~ .*\.(php|php5)?$”之前,这样会先处理(猜测)。
然后补充一下重定向的问题,直接修改nginx.conf文件,在所有location之前加入,比如我们需要把www的域名转向成不带的www的,下面是我用到的代码:
if ($host = "www.lordong.net") { rewrite ^/(.*)$ http://lordong.me/$1 permanent; } if ($host = "www.lordong.me") { rewrite ^/(.*)$ http://lordong.me/$1 permanent; } if ($host = "taobao.lordong.me") { rewrite . http://shop62429159.taobao.com permanent; }
以此为参考再做扩充吧。
试用啊,不知以后是否有机会用到。