nginx异常处理

1、nginx不转发消息头header问题

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-Server $host;

2、nginx 反向代理 proxy_set_header 自定义 header 头无效

String staffId = request.getHeader("staffId");

String sn = request.getHeader("sn");

String site_id = request.getHeader("site_id");

String photo_type = request.getHeader("photo_type");

前两个参数都可以获取,后两个参数通过nginx代理后始终为null。原因是nginx对自定义的header name的字符做了限制,默认underscores_in_headers为off,表示如果header name中包含下划线,则忽略掉,部署后就获取不到。

解决方案:

  • 在header里不要用 “_” 下划线,可以用驼峰命名或者其他的符号(如减号-)代替。nginx默认忽略掉下划线可能有些原因。

  • 在nginx里的 nginx.conf文件中配置http的部分添加:underscores_in_headers on;(默认值是off)

3、Nginx不识别中文

用windows记事本打开文件再保存会保存为UTF-8 BOM编码。这个编码在nginx中是不能被识别中文的。

我们只需要用notepad打开nginx.conf,选择编码为UTF-8无BOM编码后,查看中文显示是否正常,然后按Ctrl+s保存文件即可。

4、memc_nginx+srcache_nginx+memcached 遇到的问题

在使用 memc_nginx+srcache_nginx+memcached 时,出现了 memcached 只缓存响应头,响应主体却丢失了。具体文章参见:《memc_nginx+srcache_nginx+memcached 构建透明的动态页面缓存》。

缓存的内容被截断了。

查了些文档是由 upstream 响应截断时不报错导致的。

解决办法:

1. 打上下面的补丁

https://github.com/agentzh/ngx_openresty/blob/master/patches/nginx-1.4.2-upstream_truncation.patch

2. 使用最新版的 nginx

nginx 在 1.5.3 版本修复了这个 bug。

nginx purge 更新缓存 404 错误

nginx 默认安装就会带有反向代理的功能,但想要更好的使用,还得配备 frickle.com 的 ngx_cache_purge 模块,用于清除指定 URL 的缓存。 ngx_cache_purge 在安装的 nginx 的时候一起编译进去了,缓存功能一直正常。

文件地址: www.abc.com/includes/templates/zcen/buttons/english/button_in_cart.gif

如下图:

nginx purge 清理缓存失败

但是清理缓存的时候竟然会 404

地址: www.abc.com/purge/includes/templates/zcen/buttons/english/button_in_cart.gif

百思不得其解,网上遇到 nginx 清理缓存出现 404 的用户不在少数,网上一共有如下 3 中情况:

1、 ngx_cache_purge 版本与 nginx 版本不匹配

换了一个版本的 purge,发现依旧无效

2、 nginx 启动方法不对

很多人安装完 nginx,仅仅 reload 一次 nginx,实际上应该 stop 之后在 start。这不是我的解决方法。

3、 purge 未编译到 nginx 中

肯定不是这个问题, nginx –V 能查看编译参数

因为有其他事情,这个事情暂且搁置了,一天闲来无事,看着 nginx 的配置文件发呆,突然发现自己犯了一个很

大的错误: purge 的 location 放错了位置。

错误配置文件:

location /

{

proxy_pass http://xxx.ttlsa.com;

include proxy.conf;

}

location ~ .*\.(png|jpg|gif|GIF|jpeg|JPG|PNG|bmp|BMP|JPEG)?$

{

include proxy.conf;

proxy_pass http://xxx.ttlsa.com;

expires 1h;

access_log off;

}

location ~ /purge(/.*)

{

allow 127.0.0.1;

allow 192.168.12.0/24;

proxy_cache_purge cache_one $host$1$is_args$args;

}

正确配置文件:

location /

{

proxy_pass http://xxx.ttlsa.com;

include proxy.conf;

}

location ~ /purge(/.*)

{

allow 127.0.0.1;

allow 192.168.12.0/24;

proxy_cache_purge cache_one $host$1$is_args$args;

}

location ~ .*\.(png|jpg|gif|GIF|jpeg|JPG|PNG|bmp|BMP|JPEG)?$

{

include proxy.conf;

proxy_pass http://xxx.ttlsa.com;

expires 1h;

access_log off;

}

细心的兄弟很快能发现我把 purge 的位置放错了,每次更新图片缓存的时候它都只匹配到了图片后缀的

location,接着就返回了 404,根本没有匹配到 purge 这个 location 的机会。把 purge 调到前面就正常了。