[关闭]
@yanglt7 2018-10-21T15:54:40.000000Z 字数 2247 阅读 701

【Web 集群实战】10_Nginx rewrite

Web集群实战


1. Nginx rewrite 语法

rewrite 指令语法

regex 常用正则表达式字符

字符 描述
\ 将下一个字符标记为一个特殊字符、或一个原义字符、或一个向后引用、或一个八进制转义符。例如,“n” 匹配字符 “n”。“\n” 匹配一个换行符。序列 “\\” 匹配 “\” 而 “\(” 则匹配 “(”
^ 匹配输入字符串的开始位置。如果设置了 RegExp 对象的 Multiline 属性,^ 也匹配“\n”或“\r”之后的位置。
$ 匹配输入字符串的结束位置。如果设置了 RegExp 对象的 Multiline 属性,$ 也匹配 “\n” 或 “\r” 之前的位置
* 匹配前面的子表达式零次或多次。例如,zo* 能匹配 “z” 以及 “zoo”, * 等价于{0,}
+ 匹配前面的子表达式一次或多次。例如,“zo+” 能匹配 “zo” 以及 “zoo”,但不能匹配 “z”。+ 等价于{1,}
? 匹配前面的子表达式零次或一次。例如,“do(es)?” 可以匹配 “do” 或 “does” 中的 “do”。? 等价于{0,1}
. 匹配除 “\n” 之外的任何单个字符。要匹配包括 “\n” 在内的任何字符,请使用像 “[.\n]” 的模式
(pattern) 匹配 pattern 并获取这一匹配。所获取的匹配可以从产生的 Matches 集合得到,在 VBScript 中使用 SubMatches 集合,在 JS 中则使用 $0…$9 属性

flag 标记的说明

flag 标记符号 说明
last 本条规则匹配完成后,继续向下匹配新的 location URI 规则
break 本条规则匹配完成后,终止匹配,不再匹配后面的规则
redirect 返回302临时重定向,浏览器地址会显示跳转后的URL地址
permanent 返回301永久重定向,浏览器地址会显示跳转后的URL地址

2. Nginx rewrite 301 跳转

  1. server {
  2. listen 80;
  3. server_name yangyangyang.org;
  4. rewrite ^/(.*) http://www.yangyangyang.org/$1 permanent;
  5. }
  6. server {
  7. listen 80;
  8. server_name www.yangyangyang.org;
  9. location / {
  10. root html/www;
  11. index index.html index.htm;
  12. }
  13. access_log logs/access_www.log main gzip buffer=32k flush=5s;
  14. }

3. Nginx rewrite 不同域名的 URL 跳转

例 1 实现访问 http://blog.yangyangyang.org 时跳转到 http://www.yangyangyang.org/blog/ylt.html

  1. [root@ylt001 conf]# cd ../html/www
  2. [root@ylt001 conf]# mkdir -p blog
  3. [root@ylt001 conf]# vi ../html/www/blog/ylt.html
  4. [root@ylt001 conf]# cat ../html/www/blog/ylt.html
  5. hello!
  1. #www virtualhost by ylt
  2. server {
  3. listen 80;
  4. server_name blog.yangyangyang.org;
  5. location / {
  6. root html/blog;
  7. index index.html index.htm;
  8. }
  9. if ( $http_host ~* "^(.*)\.yangyangyang\.org$") {
  10. set $domain $1;
  11. rewrite ^/(.*) http://www.yangyangyang.org/$domain/ylt.html break;
  12. }
  13. }

例 2 实现访问 http://yangyangyang.org/bbs 时跳转到 http://bbs.yangyangyang.org

  1. #www virtualhost by ylt
  2. server {
  3. listen 80;
  4. server_name www.yangyangyang.org yangyangyang.org;
  5. location / {
  6. root html/www;
  7. index index.html index.htm;
  8. }
  9. rewrite ^/(.*)/bbs http://bbs.yangyangyang.org break;
  10. access_log logs/access_www.log main gzip buffer=32k flush=5s;
  11. }
  1. #bbs virtualhost by ylt
  2. server {
  3. listen 80;
  4. server_name bbs.yangyangyang.org;
  5. location / {
  6. root html/bbs;
  7. index index.html index.htm;
  8. }
  9. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注