一、nginx 简单的重写

 1、将*.XXX.com的域名重定向到www.XXX.com 301重写
 
 
  1. server_name  test1.abc.com *.abc.com; 
  2. index index.html index.htm index.php; 
  3. root  /home/test1.abc.com/root/; 
  4. if ($host != test1.abc.com) 
  5.    {rewrite ^/(.*)$ http://www.abc.com/$1 permanent;} 
 2、如果不存在这个文件或目录重定向到指定的目录下对应的文件中去:
 
  1. if(!-d $request_filename) 
  2. {rewrite ^/img/(.*)$ /sql/$1 last;} 
 3、限制某类文件的访问
 
  1. location ~ abc.sql 
  2.     {deny all;} 
  3. ~ 表示区分大小写 
  4. ~* 表示不区分大小写 
  5. 如果不想区分大小写 即为 
  6. location ~* abc.sql 
  7.     {deny all;} 
二、nginx 添加密码认证
1、在server段添加
 
  1. location ^~ /sql/ { 
  2.        auth_basic "test_login"; 
  3.        auth_basic_user_file /home/test1.abc.com/htpasswd; 
  4.                    } 
2、apache 自带的htpasswd 用于基本认证的存储用户名:密码的文本文件。如果htpasswd  不能读写此文件,就返回错误代码,而不做任何修改
           确定能够使用htpasswd这个命令 如果没有尝试安装httpd来获取 
           yum install httpd
           htpasswd文件生成方法:
           htpasswd -bdc
/home/test1.abc.com/htpasswd NAME PASSWD
                    -d 使用crypt()对密码加密
                    -b 使用批处理方式。直接从命令行获取密码而不进行提醒。使用这个选项需                        要特别注意。因为命令行中的密码是清晰可见的
                     -c 如果不存在文件就自动创建,如果已经存在就覆盖里面的内容。建议第                         一次生成用户时使用
   这里有个生成用户密码的脚本
 
 
  1. #!/bin/bash 
  2. read -p "press name :" name; 
  3. read -p "press password for the name: " passwd; 
  4. if [ -f /home/test1.abc.com/htpasswd ]; then 
  5. htpasswd -bd /home/test1.abc.com/htpasswd $name $passwd; 
  6. else 
  7. htpasswd -bdc /home/test1.abc.com/htpasswd $name $passwd; 
  8. fi 
  9. ##end### 
访问截图:
 

三、扩展:
    可以在 location ^~ /sql/{} 里嵌套location 以实现认证及限制文件访问功能
 
 
  1. location ^~ /sql/ { 
  2.                 auth_basic "test_login"; 
  3.                 auth_basic_user_file /home/test1.abc.com/htpasswd; 
  4.                  location ~* data.sql 
  5.                     {deny all;} 
  6.                 }