---
title: "nginx的url rewrite配置的小错误"
author: "dynamiclu"
date: "2012-01-11T16:23:06Z"
tags: []
categories: ["企业架构"]
slug: "nginx-url-rewrite"
draft: false
lastmod: "2012-05-15T17:15:09Z"
id: 1341469
url: "https://dynamiclu.iteye.com/blog/1341469"
---

\[文章作者：狂奔的鹿(陆松林) 本文版本：v1.0  转载请注明原文链接：[http://dynamiclu.iteye.com/](http://dynamiclu.iteye.com/)]

 

近期在作一个nginx换apache的项目，涉及到url的rewrite,  关于两者的区别, 这边就不提了, google一下，到处都是。

值得一提的是：

apache里的RewriteCond 转化成nginx的配置时， 都说用if并OK；

若是：

apache:

 

```
RewriteCond %{QUERY_STRING} ^search_content=(.*)$
RewriteRule  ^/search.jspa$ http://abc.domian.cn/search.jsp?search_content=%1 [L,NC,NE,R=301]
```

 

转化成nginx:

```
rewrite "^/search.jspa$" http://abc.domian.cn/search.jsp?search_content=$1 permanent;
```

 

 

如果是：

```
RewriteCond %{QUERY_STRING} ^id=(.*)$
RewriteRule  ^/search.jspa$ http://abc.domian.cn/html_%1.html [L,NC,NE,R=301]
```

仔细看一下，还原成伪链接

方式1：

```
rewrite "^search.jspa$"  http://istock.jrj.com.cn/html_$1.html permanent;
```

 配置文件不报错，但始终无效。

 

换方式2：

```
if($query_string ~ ^id=(.*)$) {
   set $id_tmp $1;
   rewrite "^/remen/sortsearch.jspa$"  http://abc.domian.cn/html_$id_tmp.html permanent;
}
```

 报错如下图：

![](http://dl.iteye.com/upload/attachment/0061/9886/3d9cef05-ec2f-3a6b-b943-3539ccb2f70a.jpg)

google了近一个小时，没发现是哪的错， 怀疑起nginx的全局变量$query\_string, 添加到log\_format里，日志能打印出来。

无意中，比较一下if的差别，才发现原来是"if("写错了，中间需要多一个空格，需要写成"if ("才成。

方式2的配置改成:

```
if ($query_string ~ ^id=(.*)$) {
   set $id_tmp $1;
   rewrite "^/remen/sortsearch.jspa$"  http://abc.domian.cn/html_$id_tmp.html permanent;
}
```

 

OK, 终于通过了。 开发出身的人，if then else写多了，系统配置时很容易犯这些错误。

 

   \[文章作者：狂奔的鹿(陆松林) 本文版本：v1.0  转载请注明原文链接：[http://dynamiclu.iteye.com/](http://dynamiclu.iteye.com/)]