nginx

更新日期: 2015-12-12 阅读次数: 15634 分类: Nginx

参考

uwsgi timeout

nginx 的配置更新:

uwsgi_read_timeout 300;

默认为 60 秒,容易会超时。

uWSGI 的日志中会看到以下错误

write(): Broken pipe [plugins/python/wsgi_subhandler.c line 132] writev(): Broken pipe [plugins/python/wsgi_headers.c line 205]

uwsgi read timeout

user www-data;

格式

user user_name group_name;

为什么不要用 root?

如果使用 root,nginx 便拥有了更改整个文件系统的权限。 非常危险,容易被黑客利用漏洞入侵之后,修改或者窃取信息。

worker_processes 4;

用于指定 worker 进程的数量。

标准配置是,one process per CPU core, 即,有多少个核就启多少个 worker 进程。

如何查看,CPU 的核数

Ubuntu 12.04

$ cat /proc/cpuinfo

里面有几个 processor, 就代表有几个核。

核数过多的情况下,可以使用

$ grep -c processor /proc/cpuinfo

site-available 与 site-enabled 的区别

include /etc/nginx/sites-enabled/*;

合理的做法是,先在 sites-available 下建立一个配置文件。然后在 sites-enabled 下创建一个指向它的软链接。

这样做的好处是,当想禁用一个配置文件的时候,直接删除软链接即可。

ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/myapp

参考: How do I add new site/server_name in nginx?

检测配置文件

不要相信网上的教程,做一下测试先

$ nginx -t

配置二级域

为什么要配置二级域? 例如,quote.sunzhongwei.com 相对 sunzhongwei.com/quote/ 的优势:

  • 采用二级域就可以在域名解析商那里(例如 DNSPod)将其指向不同 IP 的服务器, 方便以后扩展
  • 缩短服务端 routing path 的长度

如何配置:

server {
    listen       80;
    server_name  *.example.org;
    ...
}

然后需要在授权 DNS 解析商那里(例如,DNSPod)增加一条解析记录, quote.sunzhongwei.com 指向主机的 IP。

从 How nginx processes a request 那篇文档可知,Nginx 是依据请求头里的 Host 参 数的值来匹配的,所以模拟请求的时候,一定要加上 Host 头。

参考:

  • http://nginx.org/en/docs/http/server_names.html
  • http://nginx.org/en/docs/http/request_processing.html
  • http://stackoverflow.com/questions/11773544/nginx-different-domains-on-same-ip

为什么 web 服务最好结合 Nginx 使用

例如,我用 Golang 写一个服务,是否前面加一层 Nginx 呢? 使用 Nginx 的好处是什 么?

  • 因为使用 80 端口需要 root 权限,所以使用了 Nginx, 就可以避免 Golang 的服务使用 root 帐号
  • 如果多个 web 服务要使用 80 端口,就只能用 Nginx 了。

Nginx Forward Proxy

用于请求转发

server {
    listen 80;
    server_name www.sunzhongwei.com;

    location / {
      resolver 8.8.8.8;
      proxy_pass $scheme://42.96.145.169$uri$is_args$args;
    }
}

使用 Nginx 限制某些 IP 的访问

ngx_http_access_module 自带模块包含这个功能

deny <IP>;

参考:

如何查看 Nginx 对应的 OpenSSL 版本

  • http://nginx.com/blog/nginx-and-the-heartbleed-vulnerability/

Log Rotation with logrotate

Ubuntu 自带了 logrotate 程序,其他系统需要自己安装。

查看 /etc/logrotate.d/nginx 这个配置文件

# 测试方法
# /usr/sbin/logrotate -f /etc/logrotate.d/nginx
/data/logs/*.log {
        # 每天 rotate
        daily
        # 忽略丢失的日志文件,处理下一个
        missingok
        # 日志最多被 rotate 的次数
        rotate 10
        compress
        delaycompress
        notifempty
        create 0640 root root
        # 当有多个日志匹配时,下面的脚本只执行一次,防止跑多次
        sharedscripts
        # nginx will re-open its logs in response to the USR1 signal
        postrotate
                [ -s /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
        endscript
}

Nginx Cache 问题

问题:

更新了网页后,在客户端看到的网页依然是旧的。只有手动刷新才能看到最新的页面。

解决方法:

Nginx location 的匹配逻辑

Understanding Nginx Server and Location Block Selection Algorithms

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式