前两天简单整理了下Nginx的URL Rewrite基本指令,今天谈谈Nginx Rewrite的location正则表达式。 1.Nginx Rewrite 基本标记(flags)
last 相当于Apache里的[L]标记,表示完成rewrite
break 本条规则匹配完成之后,终止匹配,不再匹配后面的规则。 redirect 返回302临时重定向 地址栏会显示跳转后的地址
permanent 返回301永久重定向 地址栏会显示跳转后的地址 2、正则表达式:
1)变量名,错误的值包括:空字符串“”,或者任何以0开始的字符串。 (2)变量比较可以使用“=”和“!=”(等于和不等于)运算符 (3)正则表达式模式匹配可以使用“~”和“~*”符号 (4)~ 为区分大小写匹配 (5)~* 为不区分大小写匹配 文件以及目录匹配: (6)!~和!~*分别为区分大小写不匹配及不区分大小写不匹配
(7)-f和!-f用来判断是否存在文件
(8)-d和!-d用来判断是否存在目录 (9)-e和!-e用来判断是否存在文件或目录 (10)-x和!-x用来判断文件是否可执行: 3、案例: 3.1)需要将网站以https形式访问 server {
listen 80;
server_name www.xxx.com;
rewrite ^(.*)$ https://$host$1 permanent;
}
小提示:百度是通过index.html刷新网页,更巧妙一些。
1
2
3
| <html>
<meta http-equiv="refresh" content="0;url=https://baidu.com/">
</html>
|
3.2)Nginx Redirect将所有xxx.com与abc.xxx.com域名全部自跳www.xxx.com
1
2
3
4
5
6
7
8
9
10
| server {
listen 80;
server_name xxx.com abc.xxx.com;
index index.html index.php;
root /var/InfiNET/web/;
if ($http_host !~ "^www\.xxx\.com$") {
rewrite ^(.*) http://www.xxx.com$1 redirect;
... ............
}
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}
|
[size=1em]3.4.2)[size=1em]匹配.php代理到后端
1
2
3
4
5
| location ~ .*.PHP?$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
}
|
3.5) Nginx exprires 缓存 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| location ~ .*\.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$ {
expires 30d;
}
location ~ .*\.(js|css)?$ {
expires 12h;
}
}
# 根据文件类型
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
if (-f $request_filename) {
root /html/web/bbs;
expires 1d;
break;
}
}
#根据目录类型
location ~ ^/(images|javascript|js|css|flash|media|static)/ {
root /html/web;
expires 30d;
}
|
3.6)nginx防盗链
1
2
3
4
5
6
7
8
| #Preventing hot linking of images and other file types
location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip)$ {
valid_referers none blocked server_names *.chinarenservice.com http://localhost baidu.com;
if ($invalid_referer) {
rewrite ^/ http://www.xxx.com/images/default/logo.gif;
# return 403;
}
}
|
3.7)Nginx禁止访问下载某类型的文件
3.7.1)Nginx 下禁止访问*.txt 文件,配置方法如下.代码:
1
2
3
4
5
6
| location ~* \.(txt|doc)$ {
if (-f $request_filename) {
root /html/test;
break;
}
}
|
3.7.2)禁止访问某个目录
1
2
3
| location ~ ^/(tomcat)/ {
deny all;
}
|
3.7.3)禁止下载以点开头的文件:如 .freeke;.dat;.exe
1
2
3
| location ~ /\..+ {
deny all;
}
|
|