nginx地址重写rewrite
1.nginx重写rewrite
1.rewrite相关语句
- if
- rewrite
- set
- return
2.if语句
-
应用环境
server,location
-
语法
if () #可以支持: ~ #正则匹配(区分大小写) ~* #正则匹配(不区分大小写) !~ #正则不匹配(区分大小写) !~* #正则不匹配(不区分大小写)
2.常用nginx全局环境变量
$host #请求信息中的"host"
$request_uri #当前请求的文件路径名
$request_filename #当前请求的文件路径名(带网站的主目录)
3.匹配参考示例
配置位置:/etc/nginx/conf.d/default.conf
IP | 192.168.222.131 |
---|
#http://192.168.222.131/takehaye/1.html ===> http://192.168.222.131/yhb/2.html
[root@localhost ~]# vim /etc/nginx/conf.d/default.conf
server {
listen 80;
server_name _;
location /takehaye {
root /usr/share/nginx/htnml;
index 1.html index.html;
rewrite .* /yhb/2.html;
}
location /yhb {
root /usr/share/nginx/html;
index 2.html index.html;
}
}
#创建测试文件与测试页面
[root@localhost ~]# mkdir /usr/share/nginx/html/takehaye
[root@localhost ~]# mkdir /usr/share/nginx/html/yhb
[root@localhost ~]# echo takehaye > /usr/share/nginx/html/takehaye/1.html
[root@localhost ~]# echo yhb > /usr/share/nginx/html/yhb/2.html
#http://192.168.222.131/takehaye ==> http://www.baidu.com
#http://192.168.222.131/yhb ==> http://rog.asua.com.cn
server {
listen 80;
server_name _;
location / {
if ($uri ~* takehaye) {
return http://www.baidu.com;
}
if ($uri ~* yhb) {
return http://rog.asua.com.cn;
}
}
}
4.return指令
return指令用于返回状态码给客户端
应用实例
server {
listen 80;
server_name _;
location / {
root /usr/share/nginx/html;
index index.html
}
location ~* \.sh {
return 403;
}
}
2.nginx的location指令
1.结构
http { #协议级别
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 0;
#gzip on;
server { #服务级别
listen 80;
server_name _;
location / { #请求级别
root /html;
}
}
}
2.location前缀含义
#表示精确匹配:=
#表示匹配uri路径:^~
#表示正则匹配(区分大小写):~
#表示正则匹配(不区分大小写):~*
#表示不匹配正则(区分大小写):!~
#表示不匹配正则(不区分大小写):!~*
#通用匹配:/
3.nginx日志
日志路径:/var/log/nginx
指令中一些常用的变量
$remote_addr, $http_x_forwarded_for #记录客户端IP地址
$remote_user #记录客户端用户名称
$reques #记录请求的URL和HTTP协议
$status #记录请求状态
$time_local #通用日志下的本地时间
动态查看日志
[root@localhost ~]# tail -f /var/log/nginx/error.log