如何在nginx中重写URI?

请考虑我的根目录中的以下目录结构:

/resources/css /resources/js /resources/templates /resources/images 

我想从上面的目录服务静态内容,但我也想要这样的重写工作:

 rewrite ^/([az]+)(.*)$ /index.php?p1=$1&p2=$2; 

例如myurl.com/register/...被重写为myurl.com/index.php?p1=register&p2=...

但是这个规则也会重写/resources/ ,那么如何从重写中排除/resources呢? 或者我需要另外重写? 没有任何我试过似乎很明显,我不理解的东西。

下面的configuration是我发现的作品,因为位置语句都是相同的优先顺序,他们按顺序检查。

这帮助我了解了位置块的优先级:

 location = <path> (longest match wins) location ^~ <path> (longest match wins) location ~ <path> (first defined match wins) location <path> (longest match wins) 

这是configuration:

 // match all css/js/images in resource path location ~ ^/resources { root /mypath/myurl.com; try_files $uri =404; break; } // allow myurl.com/register etc: location ~ ^/([az]+)/(.*)$ { root /mypath/myurl.com; rewrite ^/([az]+)(.*)$ /index.php?p1=$1&p2=$2; } // everything else: location ~ / { root /mypath/myurl.com; index index.php; } 

意见欢迎!

你可以使用这个例子:

 if ($http_user_agent ~ MSIE) { rewrite ^(.*)$ /msie/$1 break; } if ($http_cookie ~* "id=([^;] +)(?:;|$)" ) { set $id $1; } if ($request_method = POST ) { return 405; } if ($slow) { limit_rate 10k; } if ($invalid_referer) { return 403; } if ($args ~ post=140){ rewrite ^ http://example.com/ permanent; } 

有关更多信息,请访问: http : //wiki.nginx.org/HttpRewriteModule

您可以为该URI添加另一个位置处理程序,以匹配存在的文件 – 如果不存在,则会中断。

 location ~* /resources/(css|js|templates|images) { if (!-f $request_filename) { break; } root /path/to/resources; } rewrite ^/([az]+)(.*)$ /index.php?p1=$1&p2=$2;