nginx的url重写[rewrite规则和参考]

本日志内容来自互联网和平日使用经验,整理一下方便日后参考。

Nginx Rewrite 相关指令有 if、rewrite、set、return 等。
if 的语法 应用于 server 和 location 环境内

if(condition){...}

if可以支持的正则表达式匹配符号有:

1、~ 为区分大小写匹配

2、~* 为不区分大小写匹配

3、!~和!~*分别为区分大小写不匹配及不区分大小写不匹配

文件及目录匹配有:

1、-f和!-f用来判断是否存在文件

2、-d和!-d用来判断是否存在目录

3、-e和!-e用来判断是否存在文件或目录

4、-x和!-x用来判断文件是否可执行

if环境下每行rewrite指令最后应该跟一个flag标记,支持的flag标记有:

1、last 相当于Apache里的[L]标记,表示完成rewrite

2、break 终止匹配, 不再匹配后面的规则

3、redirect 返回302临时重定向 地址栏会显示跳转后的地址

4、permanent 返回301永久重定向 地址栏会显示跳转后的地址

  last 和 break 标记的区别在于,last 标记在本条 rewrite 规则执行完后,会对其所在的server { … } 标签重新发起请求,而 break 标记则在本条规则匹配完成后,停止匹配,不再做后续的匹配。另有些时候必须使用 last,比如在使用 alias 指令时,而使用 proxy_pass指令时则必须使用 break。

location /abc/ {

  rewrite "^/abc/(.*).html$"    /abc/index.html    last;

}

=============应该将上面的last改为break,否则引起死循环=============

  redirect 和 permanent 区别则是返回的不同方式的重定向,对于客户端来说一般状态下是没有区别的。而对于搜索引擎,相对来说 301 的重定向更加友好,如果我们把一个地址采用 301 跳转方式跳转的话,搜索引擎会把老地址的相关信息带到新地址,同时在搜索引擎索引库中彻底废弃掉原先的老地址。
  使用 302 重定向时,搜索引擎(特别是 google)有时会查看跳转前后哪个网址更直观,然后决定显示哪个,如果它觉的跳转前的 URL 更好的话,也许地址栏不会更改,那么很有可能出现 URL 劫持的现像。
  我们在做 URI 重写时,有时会发现 URI 中含有相关参数,如果需要将这些参数保存下来,并且在重写过程中重新引用,我们可以用到 () 和 $N 的方式来解决。

例如下面设定nginx在用户使用ie时将重定向到/nginx-ie目录下:

if ($http_user_agent ~ MSIE) {

     rewrite ^(.*)$    /nginx-ie/$1    break;

}

匹配访问的url地址是个目录,则自动加“/”

if (-d $request_filename){

     rewrite  ^/(.*)([^/])$    http://$host/$1$2/     permanent;

}

[PS:一般在location中即(location /{.....})或直接在server标签中编写rewrite规则,推荐使用last标记,在非根location中(location /cms/{....}),则使用break标记]

==============实例=================

 

禁止htaccess

location ~/.ht {

      deny all;

}

禁止多个目录

location ~ ^/(cron|templates)/ {

     deny all;

     break;

}

禁止以/data开头的文件
可以禁止/data/下多级目录下.log.txt等请求;

location ~ ^/data {

      deny all;

}

禁止单个目录
不能禁止.log.txt能请求

location /searchword/cron/ {

     deny all;

}

禁止单个文件

location ~ /data/sql/data.sql {

      deny all;

}

给favicon.ico和robots.txt设置过期时间;
这里为favicon.ico为99天,robots.txt为7天并不记录404错误日志

location ~(favicon.ico) {

    log_not_found off;

    expires 99d;

     break;

}

location ~(robots.txt) {

      log_not_found off;

      expires 7d;

      break;

}

设定某个文件的过期时间;这里为600秒,并不记录访问日志

location ^~ /html/scripts/loadhead_1.js {

      access_log   off;

       root /opt/lampp/htdocs/web;

       expires 600;

        break;

}

文件反盗链并设置过期时间
这里的return 412 为自定义的http状态码,默认为403,方便找出正确的盗链的请求
“rewrite ^/ http://leech.c1gstudio.com/leech.gif;”显示一张防盗链图片
“access_log off;”不记录访问日志,减轻压力
“expires 3d”所有文件3天的浏览器缓存

 location ~* ^.+.(jpg|jpeg|gif|png|swf|rar|zip|css|js)$ {

      valid_referers none blocked *.c1gstudio.com *.c1gstudio.net localhost 208.97.167.194;

     if ($invalid_referer) {

            rewrite ^/ http://leech.c1gstudio.com/leech.gif;

            return 412;

            break;

           }

        access_log   off;

        root    /opt/lampp/htdocs/web;

        expires 3d;

        break;

}

只允许固定ip访问网站,并加上密码

root   /opt/htdocs/www;

allow   208.97.167.194;

allow   222.33.1.2;

allow   231.152.49.4;

deny    all;

auth_basic "C1G_ADMIN";

auth_basic_user_file htpasswd;

将多级目录下的文件转成一个文件,增强seo效果,如:/job-123-456-789.html 指向/job/123/456/789.html

rewrite  ^/job-([0-9]+)-([0-9]+)-([0-9]+).html$   /job/$1/$2/jobshow_$3.html   last;

将根目录下某个文件夹指向2级目录,如:如/shanghaijob/ 指向 /area/shanghai/
如果你将last改成permanent,那么浏览器地址栏显是/location/shanghai/

rewrite ^/([0-9a-z]+)job/(.*)$    /area/$1/$2   last;

上面例子有个问题是访问/shanghai 时将不会匹配

rewrite ^/([0-9a-z]+)job$     /area/$1/      last;

rewrite ^/([0-9a-z]+)job/(.*)$    /area/$1/$2     last;

这样/shanghai 也可以访问了,但页面中的相对链接无法使用,如./list_1.html真实地址是/area/shanghai/list_1.html会变成/list_1.html,导至无法访问。

那我加上自动跳转也是不行,(-d $request_filename)它有个条件是必需为真实目录,而我的rewrite不是的,所以没有效果

if (-d $request_filename){

     rewrite ^/(.*)([^/])$    http://$host/$1$2/     permanent;

}

知道原因后就好办了,让我手动跳转吧

rewrite ^/([0-9a-z]+)job$     /$1job/     permanent;

rewrite ^/([0-9a-z]+)job/(.*)$    /area/$1/$2     last;

文件和目录不存在的时候重定向:

if (!-e $request_filename) {

        proxy_pass http://127.0.0.1;

}

域名跳转

server

{

    listen       80;

    server_name  jump.c1gstudio.com;

    index index.html index.htm;

    root    /opt/lampp/htdocs/www;

    rewrite ^/ http://www.c1gstudio.com/;

     access_log  off;

}

多域名转向

server_name  www.c1gstudio.com www.c1gstudio.net;

index index.html index.htm;

root  /opt/lampp/htdocs;

if ($host ~ "c1gstudio.net") {

        rewrite ^(.*) http://www.c1gstudio.com$1   permanent;

}

三级域名跳转

if ($http_host ~* "^(.*).i.c1gstudio.com$") {

       rewrite ^(.*) http://top.yingjiesheng.com$1;

       break;

}

域名镜像

server

{

      listen       80;

      server_name  mirror.c1gstudio.com;

      index index.html index.htm;

      root  /opt/lampp/htdocs/www;

      rewrite ^/(.*) http://www.c1gstudio.com/$1    last;

      access_log  off;

}

某个子目录作镜像

location ^~ /zhaopinhui {

      rewrite ^.+ http://zph.c1gstudio.com/     last;

      break;

}

一些可用的全局变量有,可以用做条件判断(待补全)

1、$args,待请求的参数

2、$content_length,内容大小

3、$content_type,内容类型

4、$document_root,当前请求的根路径设置值

5、$document_uri,与$uri一样,URI地址

6、$host,请求信息中的“Host”,如果没有Host行,则等于设置的服务器名

7、$http_user_agent,用户代理(客户端浏览器类型)

8、$http_cookie,cookie设置

9、$limit_rate,对连接速率的限制

10、$request_body_file,,往nginx代理服务器上传文件时,nginx创建的临时文件

11、$request_method,请求的方法,比如“GET”,“POST”等

12、$remote_addr,客户端地址

13、$remote_port,客户端端口

14、$remote_user,客户端用户名,认证用

15、$request_filename,当前请求的文件路径名

16、$request_uri

17、$query_string,与$args相同

18、$scheme,所有的协议,比如http或https

19、$server_protocol,请求的协议

20、$server_addr,服务器地址

21、$server_name,服务器名

22、$server_port,服务器端口

23、$uri,URI地址