今天一个技术前辈问我Nginx是否可以实现apache 的 .htaccess 功能。 因为之前在网络上看过类似的文章但没有实验过(不喜欢这个机制)。我不在意的回答yes。其实nginx是不支持.htaccess或则说是没有内置这么一套机制。
要实现.htaccess的这个功能,先了解下.htaccess 的执行逻辑。
很简单。Apache只要AllowOverride 开启支持.htaccess,就会在每次执行的目录中扫描(.htaccess)文件(^..^多么无语的机制).
当然 apache是每次扫描.htaccess。而nginx 是肯定不能每次扫描这个.htaccess文件了。所以只能将.htaccess 在启动是装入nginx配置。
.htaccess的特点是每次不需要重启apache就可以实现规则控制。
针对这个特点可以利用linux内核中的文件系统变化通知机制来实现动态更新nginx的配置。
1 安装inotify
参考IBM的文章(http://www.ibm.com/developerworks/cn/linux/l-inotify.html)
2 安装 inotify-tools
- wget http://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz
- tar zvxf inotify-tools-3.14.tar.gz
- cd inotify-tools-3.14
- ./configure
- make && make install
编写.htaccess 监听脚本
vim nginxhtaccess.sh
- #!/bin/sh
- inotifywait -m -e modify /usr/local/nginx/html/.htaccess | while read file
- do
- /usr/local/nginx/sbin/nginx -s reload
- Done
监听/usr/local/nginx/html/ 目录下的.htaccess 文件修改事件。当被修改后就以不暂停nginx的方式将.htaccess规则写入nginx。
如果有多个.htaccess文件 可以用
- #!/bin/sh
- inotifywait -m -e modify --fromfile /usr/local/nginx/html/allhtaccess.txt | while read file
- do
- /usr/local/nginx/sbin/nginx -s reload
- Done
汇总一个.htaccess 规则文件的地址 allhtaccess.txt
–fromfile /usr/local/nginx/html/allhtaccess.txt
3 修改nginx.conf 的配置文件
添加
- include /usr/local/nginx/html/.htaccess; //.htaccess 文件地址
4 启动nginxhtaccess.sh 监听脚本
简单的实现完毕。