rewrite重定向 这些规则可以写在server里面,也可以写在location里面相当的灵活。


所用位置:


server {
    listen 80;
    server_name www.maomaochong.com ;
    root /root;
    index index.html index.htm;
    location / {

        rewrite  ^/(.*)$   /erp/ permanent;

        proxy_pass  http://ERP/erp/;
        proxy_redirect  off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}


也可以这样:


location ~ .*\.               
 (html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|doc|ppt|pdf|xls|swf|zip|ipa|apk)$
{

if ( $request_uri  ~ /jsp/(.*)$ )
    {
     proxy_pass http://www.maomaochong.com/jsp/$1;

    }
   proxy_redirect  off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    root /var/www/webfile/; #网站静态文件放置目录
    expires      7d;
}
说明一下location静态文件配置这个地方! 因为我的静态文件放在了nginx服务器上,所以静态文件是直接调用本地得。但是唯独www.maomaochong.com/jsp/ 这个目录下的静态文件放在后端(另一台服务器上)。每次我访问www.maomaochong.com/jsp/这个地址,他调用的每次都是在/var/www/webfile/这个目录下寻找(优先调用本地,本地没有就直接报错)。所以肯定是访问不到的。所以我在这里写了一个 $request_uri 的if判断。判断请求的路径是否是/jsp/ 如果是,就交给后端处理。这这样就避免了访问jsp这个目录调用本地静态文件的问题。
rewrite符号的含义:

.*: 标示所有

^:以xx开头

$: 以xx结尾

~: 区分大小写匹配

~*: 不区分大小写匹配

!~ : 区分大小写匹配并取反

!~* : 不区分大小写匹配并取反

 +: 匹配一次或多次。和apache的类似

[0-9]: 0到9之间,[]是用来标示范围的

[a-z] : a到z之间

() : 标示变量,()里写变量内容。 $1,$2,引用的就是这个变量

([a-z]) :  这个变量标示 a到z之前的这个范围

([0-9]+) :  这个变量标示0到9之间,匹配一次或者多次。比如:2016-10-11这个字符串要写变量匹配就是  ([0-9]+)                -([0-9]+)-([0-9]+) 第8个案例有这个用法

$host :  主机名字

$request_filename  :  请求的文件名字

$request_uri  :  请求的uri地址
1,将www.myweb.com/connect 跳转到connect.myweb.com
   answer: rewrite /connect/(.*)  /$1  permanent;
2,将connect.myweb.com 301跳转到www.myweb.com/connect/
    if ($host = connect.myweb.com) {
     rewrite /(.*) http://www.myweb.com/connect/ permanent; 
    }
3,myweb.com 跳转到www.myweb.com
if ($host = myweb.com) {
  rewrite ^/(.*)$ http://www.myweb.com/$1 permanent; 
  }
4,www.myweb.com/category/123.html 跳转为 tutu/123.html
rewrite /category/([0-9]+).html  /tutu/$1.html  permanent;
5. www.myweb.com/admin/ 下内容(xx)跳转为www.myweb.com/admin/index.php?s=xx
if(-e $request_filename){
     rewrite /admin/(.*) /admin/index.php?s=$1  permanent; 
    }
6.www.myweb.com/xinwen/123.html  等xinwen下面数字+html的链接跳转为404
    rewrite /xinwen/([0-9]+).html /404.html  permanent;
7,重定向http://www.myweb.com/123/456.php 链接为404页面
    rewrite /123/456.php /404  permanent;
8.http://www.myweb.com/news/activies/2014-08-26/123.html 跳转为 http://www.myweb.com/news/2014-08-26/123.html (此类网页都需跳转)
/news/activiess/news/([0-9]+)-([0-9]+)-([0-9]+)/(.*) /news/$1-$2-$3/$4  permanent;

 https://blog.51cto.com/maomaochong/1866381