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