nginx之rewrite规则未加引号导致检查nginx语法报错

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nginx之rewrite规则未加引号导致检查nginx语法报错相关的知识,希望对你有一定的参考价值。

在nginx的站点配置文件中使用了rewrite,检查rewrite规则确定是没问题,但是在rewrite中带有"{}"时,此时检查nginx语法报错
rewrite规则:

[[email protected] ~]# grep rewrite /usr/local/nginx/conf/vhost/img.test.conf 
   rewrite ^/.{4}[0-9]{4}[0-9]{8}/(.*)$ /uploads/picture/$1 last;

检查语法报错:

[[email protected] ~]# /usr/local/nginx/sbin/nginx -t
nginx: [emerg] directive "rewrite" is not terminated by ";" in /usr/local/nginx/conf/vhost/img.test.conf:8
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

错误原因:这是由于规则里有大括号“{ }”的符号,Nginx误以为这是规则的结尾,产生错误
解决的办法:把规则段使用单引号或者是双引号引起来

[[email protected] ~]# grep rewrite /usr/local/nginx/conf/vhost/img.test.conf 
   rewrite ‘^/.{4}[0-9]{4}[0-9]{8}/(.*)$‘ /uploads/picture/$1 last;

或者:

[[email protected] ~]# grep rewrite /usr/local/nginx/conf/vhost/img.test.conf 
   rewrite "^/.{4}[0-9]{4}[0-9]{8}/(.*)$" /uploads/picture/$1 last;
[[email protected] ~]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

此规则简单说明:

.{4}指的是任意4个字符,[0-9]{4}任意4个数字,[0-9]{8}任意8个数字

应用环境说明:
此服务器充当图片服务器,由nginx来提供服务,应用配置环境如下:

[[email protected] ~]# grep root /usr/local/nginx/conf/vhost/img.test.conf 
   root  /data/www/images;
[[email protected] ~]# ll /data/www/images/uploads/picture/2016/07/28/1469696883.jpeg 
-rw-r--r--. 1 root root 65824 Jul 28  2016 /data/www/images/uploads/picture/2016/07/28/1469696883.jpeg
[[email protected] ~]# ll /data/www/images/uploads/picture/2016/07/28/1520924032.png 
-rw-r--r--. 1 root root 89032 Mar 13 14:53 /data/www/images/uploads/picture/2016/07/28/1520924032.png
[[email protected] ~]# 

浏览器请求图片,此时图片正常显示:


http://img.test.com/MTEy114512345678/2016/07/28/1469696883.jpeg
http://img.test.com/MTEy114512345678/2016/07/28/1520924032.png 

技术分享图片

以上是关于nginx之rewrite规则未加引号导致检查nginx语法报错的主要内容,如果未能解决你的问题,请参考以下文章

Nginx 之 Rewrite 规则

前端开发掌握nginx常用功能之rewrite

Nginx的rewrite应用

Nginx高级应用--负载均衡rewrite规则

Nginx之location和rewrite

Nginx学习笔记14rewrite之permanent永久重定向