nginx支持.htaccess文件实现伪静态的方法

方法如下:

1. 在需要使用.htaccess文件的目录下新建一个.htaccess文件,

vim /var/www/html/.htaccess

2. 在里面输入规则,我这里输入Discuz的伪静态规则:

# nginx rewrite rule

rewrite /!.(js|gif|jpg|png|css)$ /index.php;

# end nginx rewrite rule

wq保存退出。

3. 修改nginx配置文件:

vim /etc/nginx/nginx.conf

4. 在需要添加伪静态的虚拟主机的server{}中引入.htaccess文件,如图所示:

server {
        listen       8081;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            #root   html;
                        root   D:/www; 
                        include D:/www/.htaccess;
            index  index.php,index.phtml,index.html index.htm;
                        if (!-e $request_filename){
                                        rewrite ^/(.*)$ /index.php last;
                        }
        }
                
                location ~ \.ht { 
                        deny  all; 
                }
                
                # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
                #
                location ~ \.php$ {
                          root           D:/www;
                          fastcgi_pass   127.0.0.1:9000;
                          fastcgi_index  index.php;
                          fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                          include        fastcgi_params;
                }
}

  

include /var/www/html/.htaccess;(把这个改成你.htaccess文件的具体位置)

wq保存退出。

5. 重新加载nginx配置文件:

/etc/init.d/nginx reload

重新打开网页看看,如果伪静态正常就证明你的rewrite rule语法是正确的。

正常,完毕!

补充:偶在网上发现了个可以在线将Apache Rewrite伪静态规则自动转换为Nginx Rewrite网页。大家可以试试看。

http://www.anilcetin.com/convert-apache-htaccess-to-nginx/

此地址里面的内容包含可以完成上面说的略做修改的功能。就是把.htaccess中的规则自动转换成nginx下面可用的规则。

总结:.htaccess文件本来是apache专用的分布式配置文件,提供了针对每个目录改变配置的方法,即在一个特定的目录中放置一个包含指令的文件,其中的指令作用于此目录及其所有子目录。其实修改一下,nginx也可使用.htaccess文件实现多种功能。实现伪静态只是.htaccess的其中一个用途,.htaccess还可以做很多的用途,如过滤访问IP,设置web目录访问权限、密码等。