[乐意黎原创]Nginx里带参数的rewrite详解

版权声明:本文若为 {aerchi/乐意黎} 原创文章,未经允许不得镜像、采集博客内容。如有转载, 请务必注明来源。 https://blog.csdn.net/aerchi/article/details/84068768

1. 如下所示,带 www.daza.ren/view-detail-weixin-9999.html 和 www.daza.ren/view-detail-weixin-9999.html?65 在apache 下的写法。

1).  www.daza.ren/view-detail-weixin-9999.html

用 apache httpd htacess 的写法:

RewriteRule ^[a-zA-Z]*/detail[/-]?([a-zA-Z$]*)[/-]?([0-9a-zA-Z]*)\.html$ detail-comm.php?type=$1&ids=$2


2). www.daza.ren/view-detail-weixin-9999.html?65

用 apache httpd htacess 的写法:

RewriteCond %{QUERY_STRING} ^(.+)$
RewriteRule ^[a-zA-Z]*/detail[/-]?([a-zA-Z]*)[/-]?([0-9a-zA-Z]*)\.html$ detail-comm.php?type=$1&ids=$2&showNumber=%1



2. 现因采用Nginx ,要把形如  www.daza.ren/view-detail-9999.html 的url 改用nginx 里的 rewrite 来写。

2.1).  www.daza.ren/view-detail-weixin-9999.html

用 nginx rewrite的写法:

rewrite "^/[a-zA-Z]*/detail[/-]?([a-zA-Z$]*)[/-]?([0-9a-zA-Z]*)\.html$" /detail-comm.php?type=$1&ids=$2;

 

2.2). www.daza.ren/view-detail-weixin-9999.html?65

用 nginx rewrite的写法:

rewrite "^/[a-zA-Z]*/detail[/-]?([a-zA-Z$]*)[/-]?([0-9a-zA-Z]*)\.html$" /$1/$2/$args?;
rewrite "^/([a-zA-Z]*)[/-]?([a-zA-Z0-9]*)[/-]?([0-9]*)?" /detail-comm.php?type=$1&id=$2&showNumber=$3 last;

转发后,传递的url 如下图.  注意后缀加?与未加? 的区别。

2.2.1) 下图加未加 ?.


2.2.2) 下图加了 ?.

 

 注: 关键点就在于“?”这个尾缀。重定向的目标地址结尾处如果加了?号,则不会再转发传递过来原地址的问号?后面的参数部分(如上面的  &45)。

注: nginx rewrite正则匹配不会匹配问号后的参数,因此需要使用$arg_{参数名}来保留参数, $args 表示泛参数,且匹配规则要以问号结尾;


2.3). www.daza.ren/view-detail-typename-xxxx.html?pageno=45

用 nginx rewrite的写法:

rewrite "^/[a-zA-Z]*/detail[/-]?([a-zA-Z$]*)[/-]?([0-9a-zA-Z]*)\.html$" /$1/$2/$arg_pageno?;
rewrite "^/([a-zA-Z]*)[/-]?([a-zA-Z0-9]*)[/-]?([0-9]*)?" /detail-comm.php?type=$1&id=$2&showNumber=$3 last;

转发后,传递的url 如下图. 


2.4). 上述情况,如在 rewrite 语句 后加 permanent, 则会地址转向.




3. 首页匹配,可用.

 rewrite "^(/|/index\.html|/index\.php)$" /index.php last;

乐意黎原创
本文地址:  https://blog.csdn.net/aerchi/article/details/84068768

猜你喜欢

转载自blog.csdn.net/aerchi/article/details/84068768