一、Nginx的rewrite规则
指令:
set:设置变量
if:用来判断一些在rewrite语句中无法直接匹配的条件,比如检测文件存在与否,http header,cookie等
用法: if(条件) {…}
- 当if表达式中的条件为true,则执行if块中的语句 - 当表达式只是一个变量时,如果值为空或者任何以0开头的字符串都会当作false - 直接比较内容时,使用 = 和 != - 使用正则表达式匹配时,使用 ~ 大小写敏感匹配 ~* 大小写不敏感匹配 !~ 大小写敏感不匹配 !~* 大小写不敏感不匹配 - 使用-f,-d,-e,-x检测文件和目录 -f 检测文件存在 -d 检测目录存在 -e 检测文件,目录或者符号链接存在 -x 检测文件可执行 跟~类似,前置!则为”非”操作 return:用来直接设置HTTP返回状态,比如403,404等
break:立即停止rewrite检测
rewrite:
break – 停止rewrite检测,当含有break flag的rewrite语句被执行时,该语句就是rewrite的最终结果
last – 停止rewrite检测,但是跟break有本质的不同,last的语句不一定是最终结果.
redirect – 返回302临时重定向,一般用于重定向到完整的URL(包含http:部分)
permanent – 返回301永久重定向,一般用于重定向到完整的URL(包含http:部分)
了解了一些基本的定义下面就直接上配置。
二、nginx配置示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
| server {
listen 80;
server_name www.soul.com soul.com pay.soul.com bbs.soul.com;
root /www;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
index index.php index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
################### 二级域名自动匹配到子目录下 #######################
set $sub_domain "";
if ($http_host ~ "(.+).soul.com$") {
set $sub_domain $1;
}
if ($http_host = "www.soul.com") {
set $sub_domain "";
}
if ($sub_domain != "") {
rewrite /(.+) /$sub_domain/$1 break;
}
######################################################################
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ .php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /.ht {
# deny all;
#}
}
|
上述注释之间的配置就是让二级域名自动匹配到根目录下的域名对应的子目录。
三、开启支持PATH_INFO
1、配置文件示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| location ~ .php {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;
#############################################################
set $path_info "";
set $real_script_name $fastcgi_script_name;
if ($fastcgi_script_name ~ "^(.+?.php)(/.+)$") {
set $real_script_name $1;
set $path_info $2;
}
fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
fastcgi_param SCRIPT_NAME $real_script_name;
fastcgi_param PATH_INFO $path_info;
#############################################################
}
|
在location中加入上述注释内容之间的代码即可。代码的意思也很容易看懂。主要是设置path_info的变量。注意的是~.php没有$,否则就不会匹配到后面的参数了。
配置完成后,我们来测试看下效果:
在根目录下新建index.php文件:
1
2
3
4
5
6
7
8
9
10
| [iyunv@www]# cat index.php
echo "";
print_r($_GET);
print_r($_SERVER);
exit;
require_once('config/common.php');
Route::run();
?>
|
访问测试结果:
可以看到参数传递正常。这种格式也不会报错了。
|