• 1
  • 2
  • 3
  • 4
  • 5
阿里云主机ECS 首 页  »  帮助中心  »  云服务器  »  阿里云主机ECS
Nginx配置文件中rewrite指令的使用方法
发布日期:2016-1-11 14:1:54

  1、rewrite 指令:可使用在location, if ,server 区域;

  语法:rewrite regex replacement flag

  按照相关的正则表达式与字符串修改URL,指令按照在配置文件中出现的顺序执行。

  可在重写指令后面添加标记。

  2、使用场景:

  1)将所有的http请求通过rewrite重写到https

  server {

  listen 192.168.1.111:80;

  server_name test.com;

  rewrite ^(.*)$ https://$host$1 permanent;

  }

  该配置完成后,就可将http://test.com的请求全部重写到https://test.com上了

  2)访问www.test.com/download的请求重写到http://www2.test.com/download,如下图所示:

  

  3) 将www.test.com 301跳转到ww2.test.com/connect/

  if ($host = "www.test.com")

  { rewrite ^/(.*)$ http:// www2.test.com/connect/$1 permanent;

  }

  4)将 www.test.com /category/123.html 跳转为 category/?cd=123

  rewrite "/category/(.*).html$" /category/?cd=$1 last;

  5)将www.test.com /images/logo.jpg跳转为 http:// www2.test.com /images/logo.jpg

  rewirte "/images/\(.*\.jpg\)" http:// www2.test.com /images/$1