Nginx Location和Rewrite总结
Nginx 版本:nginx/1.10.3 (Ubuntu)
Location 部分:
第一步:创建Nginx 虚拟主机
Nginx 安装成功安装并且可以运行之后,在 /etc/nginx 目录下创建vhosts 目录,并且打开nginx.conf 文件,在http模块中,将vhosts
文件下所有以.conf文件包含进来,这样就可以在vhosts下创建不同域名的server,结构比较清晰。
include /etc/nginx/vhosts/*.conf;
server { listen 80; server_name test.com; index aa.php; root /var/www/test; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { fastcgi_pass unix:/run/php/php7.0-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }
##这里有两个location,location / 的优先级 比 location ~ \.php$ 的优先级要低
##设置的index 为aa.php
第二步:在 /etc/hosts 文件中添加 127.0.1.1 test.com
第三步:创建 /var/www/test 目录,并添加 aa.php,cc.php和index.php
第四步:实验
curl test.com/index.php
输出:index.php 说明运行的是 index.php 这个文件
解释:这里是直接匹配到了 .php 结尾的location
curl test.com 输出:aa.php 说明运行的是aa.php这个文件
解释:这里由于没有匹配到 .php结尾的location,所以匹配到了默认的 / location。 默认的location中指定了
默认文件为 aa.php。然后又使用到了try_files 这个命令。所以会重写到 test.com/aa.php。然后就会被 .php 结尾
location 匹配到。然后输出aa
其它匹配及总结:
location = / { # 精确匹配"/" } location / { # 所有location匹配之后都无法匹配的默认匹配 } location ^~ /images/ { # 匹配任何以 /images/ 开始的请求,并停止匹配 其它location } location ~* .(gif|jpg|jpeg)$ { # 匹配以 gif, jpg, or jpeg结尾的请求. # 但是所有 /images/ 将会由 ^~ /images/ 的location来匹配 }
Rewrite 部分:
rewrite只能放在server{},location{},if{}中,并且只能对域名后边的除去传递的参数外的字符串起作用。与location主要区别在于rewrite是在同一域名内更改获取资源的路径,而location是对一类路径做控制访问或反向代理.
rewrite regex replacement [flag];
regex
.
: 匹配除换行符以外的任意字符?
: 重复0次或1次+
: 重复1次或更多次*
: 重复0次或更多次\d
:匹配数字^
: 匹配字符串的开始$
: 匹配字符串的介绍{n}
: 重复n次{n,}
: 重复n次或更多次[c]
: 匹配单个字符c[a-z]
: 匹配a-z小写字母的任意一个
flag可以是如下参数 last 本条规则匹配完成之后,继续向下匹配新的location URI。 break 本条规则匹配完成之后,不再匹配后面的任何规则。 redirect 返回302临时重定向 permanent 返回301永久重定向
实例:
rewrite ^/(.*) http://www.test.com/$1 permanent;
当访问 test.com及之后的内容,会通过这条rewrite跳转到www.test.com这个域名
server_name 也可以实现相同目的 ,配置如下:
server_name test.com www.test.com