Nginx
Nginx是什么
Nginx是一款开源轻量级的Web服务器,也是一款轻量级的反向代理服务器。
Nginx (发音为“ engine x”)
Nginx一般用于作为反向代理服务器。很少作为Web服务器
- 直接支持Rails和PHP
- 作为HTTP反向代理服务器
- 作为邮件代理服务器
- 作为负载均衡服务器
- 帮助实现前端动静分离
- HTTP 缓存……
Nginx的特性
Nginx 项目始于对高并发性、高性能和低内存使用。
高稳定、高性能、资源占用少、功能丰富、模块化结构、支持热部署。
据Netcraft统计在2014年3月17.65% 的站点使用Nginx代理。
nginx优化单台机器抗10万并发
Nginx基本结构
每个worker宕掉不会影响其他进程的正常运行。
Nginx安装
必须注意的是,仓库中的包通常会过时。 如果我们想要最新的特性和BUG修复,建议从源代码编译或直接使用nginx.org提供的包。
nginx 依赖环境准备
1. GCC——GNU编译器集合
GCC可以使用默认包管理器的仓库(repositories)来安装,包管理器的选择依赖于你使用的Linux发布版本,包管理器有不同的实现:yum是基于Red Hat的发布版本;apt用于Debian和Ubuntu;yast用于SuSE Linux等等。
RedHat中安装GCC:
yum install gcc
Ubuntu中安装GCC:
apt-get install gcc
2、PCRE库
Nginx编译需要PCRE(Perl Compatible Regular Expression),因为Nginx的Rewrite模块和HTTP核心模块会使用到PCRE正则表达式语法。这里需要安装两个安装包pcre和pcre-devel。第一个安装包提供编译版本的库,而第二个提供开发阶段的头文件和编译项目的源代码,这正是我们需要的理由。
RedHat中安装PCRE:
yum install pcre pcre-devel
Ubuntu中安装PCRE:
apt-get install libpcre3 libpcre3-dev
3、zlib库
zlib库提供了开发人员的压缩算法,在Nginx的各种模块中需要使用gzip压缩。如同安装PCRE一样,同样需要安装库和它的源代码:zlib和zlib-devel。
RedHat中安装zlib:
yum install zlib zlib-devel
Ubuntu中安装zlib:
apt-get install zlib1g zlib1g-dev
4、OpenSSL库
在Nginx中,如果服务器提供安全网页时则会用到OpenSSL库,我们需要安装库文件和它的开发安装包(openssl和openssl-devel)。
RedHat中安装OpenSSL:
yum install openssl openssl-devel
Ubuntu中安装OpenSSL:(注:Ubuntu14.04的仓库中没有发现openssl-dev):
apt-get install openssl openssl-dev
CentOS安装Nginx
其他版本的Linux系统?博主只玩过CentOS啊!…………
从仓库安装
wget http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm
rpm -ivh nginx-release-centos-6-0.el6.ngx.noarch.rpm
yum install nginx
service nginx start
从源码安装
# 博主自用安装脚本
yum -y install gcc
yum -y install gcc-c++
yum install pcre pcre-devel
yum install zlib zlib-devel
wget http://nginx.org/download/nginx-x.x.x.tar.gz
tar xvzf nginx-x.x.x.tar.gz
cd nginx-x.x.x
# nginx安装
./configure --prefix=/usr/local/nginx --with-http_ssl_module
make && make install
# 将/usr/local/Nginx/sbin 目录添加PATH变量中,并检查Nginx 版本
export PATH=$PATH:/usr/local/nginx/sbin
echo $PATH
nginx -v
博主尝试全离线安装,但是gcc依赖太多,博主尝试从源码安装gcc,各种暴毙。
暴毙流博主的卸载脚本
# 停止服务
service nginx stop
# 保险起见remove一下
yum remove nginx
# whereis nginx
rm -rf /usr/local/nginx
# 删除开机启动
chkconfig nginx off
rm -rf /etc/init.d/nginx
模块选择
我们可以通过运行。 / configure – help来选择安装的模块。不幸的是,如果我们已经安装了 Nginx 并且想要添加一个特定的模块,我们将不得不卸载它并重新编译它以支持所需的模块。
HTTP 模块列表
名称 | 描述 | 版本 | 禁用参数 |
---|---|---|---|
HTTP Core | ports,locations,error pages,aliases | –without-http | |
Access | 基于 IP 地址允许 / 拒绝 | –without-http_access_module | |
Auth Basic | 基本 HTTP 认证 | –without-http_auth_basic_module | |
Auto Index | Generates automatic directory listings | –without-http_autoindex_module | |
Browser | 重新编码网页 | 0.4.3 | –without-http_browser_module |
Charset | 基本 HTTP 认证 | –without-http_charset_module | |
Empty GIF | Serve a 1×1 image from memory | 0.3.10 | –without-http_empty_gif_module |
FastCGI | 支持 FastCGI | –without-http_fastcgi_module | |
Geo | IP地址地域分发模块 | 0.1.17 | –without-http_geo_module |
Gzip | Gzip responses. | –without-http_gzip_module | |
Headers | 设置任意 HTTP 响应头 | ||
Index | 控制哪些文件将用作索引 | ||
Limit Requests | 限制客户端连接的频率 | 0.7.20 | –without-http_limit_req_module |
Limit Conn | 基于变量限制并发连接 | –without-http_limit_conn_module | |
Log | 自定义访问日志 | ||
Map | Set config variables using arbitrary key/value pairs. | 0.3.16 | –without-http_map_module |
Memcached | 支持 Memcached | –without-http_memcached_module | |
Proxy | Proxy to upstream servers. | –without-http_proxy_module | |
Referer | 基于 Referer 过滤请求 | –without-http_referer_module | |
Rewrite | 请求重写 | –without-http_rewrite_module | |
SCGI | 支持 SCGI 协议 | 0.8.42 | –without-http_scgi_module |
Split Clients | 根据一些条件拆分客户 | 0.8.37 | –without-http_split_clients_module |
SSI | Server-side includes. | –without-http_ssi_module | |
Upstream | 负载均衡组件 | –without-http_upstream_ip_hash_module (ip_hash directive only) | |
User ID | 识别 cookies | –without-http_userid_module | |
uWSGI | uWSGI协议支持 | 0.8.40 | –without-http_uwsgi_module |
X-Accel | X-Sendfile-like module |
邮件模块列表
名称 | 描述 | 版本 | 配置参数 |
---|---|---|---|
Mail Core | 邮件模块的核心参数 | –with-mail | |
POP3 | POP3设置 | –without-mail_pop3_module | |
IMAP | IMAP设置 | –without-mail_imap_module | |
SMTP | Smtp 设置 | –without-mail_smtp_module | |
Auth HTTP | 使用 Nginx 验证邮件服务 | ||
Proxy | Nginx可以代理 IMAP、 POP3和 SMTP 协议 | ||
SSL | ssl / tls 支持 | –with-mail_ssl_module |
添加 Nginx 作为系统服务
在 /etc/init.d/ 下创建名为 nginx 的启动脚本
注意转换成Unix/Linux格式
#!/bin/bash
#
# chkconfig: - 85 15
# description: Nginx is a World Wide Web server.
# processname: nginx
nginx=/usr/local/nginx/sbin/nginx
conf=/usr/local/nginx/conf/nginx.conf
case $1 in
start)
echo -n "Starting Nginx"
$nginx -c $conf
echo " done"
;;
stop)
echo -n "Stopping Nginx"
killall -9 nginx
echo " done"
;;
test)
$nginx -t -c $conf
;;
reload)
echo -n "Reloading Nginx"
ps auxww | grep nginx | grep master | awk '{print $2}' | xargs kill -HUP
echo " done"
;;
restart)
$0 stop
$0 start
;;
show)
ps -aux|grep nginx
;;
*)
echo -n "Usage: $0 {start|restart|reload|stop|test|show}"
;;
esac
注册脚本
chmod +x /etc/init.d/nginx
chkconfig --add nginx
chkconfig nginx on
OK
service nginx start
service nginx stop
service nginx restart
service nginx reload
此外,我们还需要确保 Nginx.conf 文件“知道”在哪里可以找到 Nginx 的 PID。 取消 nginx.conf 中下面一行的注释
pid logs/nginx.pid;
Nginx配置
先上干货(示例配置文件)
nginx.conf
# 博主个人使用配置模板奉上,多余的注释可删除
# 运行Nginx用户 [用户组] 防止root权限太大
user root;
# 工作进程数,设置为cpu数目,
# 如果处理大量静态文件文件大小总和超出了可用内存,则一帮配置为cpu数目的两倍
# 理论上最大连接数 = worker_processes * events.worker_connections
worker_processes 1;
# only linux 经工作进程指定到cpu,指定第一个进程给cpu1,第二个给cpu2
# worker_cpu_affinity 0001 0010 0100 1000
# 日志 crit相当于fata
error_log logs/error.log crit;
#error_log logs/error.log notice;
#error_log logs/error.log info;
# Nginx的进程号
pid logs/nginx.pid;
events {
# 使用的事件模型,linux建议epoll,操作系统的文件模型
use epoll;
# 工作进程的最大连接数,默认1024
# 浏览器默认打开2个连接,反向代理*2
# 最大连接数=worker_processes * worker_connections/4
# 建议设置为你的linux内核最大文件(65535)worker_rlimit_nofile
# linux内核每个进程能打开的最大文件数默认为1024需要手动修改。
worker_connections 1024;
}
# =====协议级别=====
# http.aio=异步文件io,开启后自动关闭sendfile(小文件)
# location.alias=别名比如 location /i/ 别名 alias 替换为 /spool/
# 需要使用$request_body 时推荐打开client_body_in_single_buffer
http {
# 引入其他配置文件
include mime.types;
#include proxy.conf;
default_type application/octet-stream;
# 日志结构 内置变量 $remote_addr $pid=进程号 ¥realpath_root= 真实路径
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# 日志记录到logs/access.log使用main格式 Nginx用户必须有写入权限
access_log logs/access.log main;
server_names_hash_bucket_size 256;
# 客户端请求 body缓冲区的大小,默认8k
client_body_buffer_size 128k;
client_header_buffer_size 8k;
# 默认5m,应用有大量上传下载时,建议修改
client_max_body_size 50m;
# 超时时间加长
client_header_timeout 1m;
client_body_timeout 1m;
large_client_header_buffers 4 8k;
# 发送时间超时
send_timeout 3m;
# 小文件建议打开,内存之间文件拷贝
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0; 长连接超时 keepalive_requests 长连接数
keepalive_timeout 120;
# keepalive socket配置
tcp_nodelay on;
tcp_nopush on;
# 压缩模块相关指令
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
# 负载均衡
upstream ydual.com {
#server 127.0.0.1:9080 weight=5
server 127.0.0.1:8080 weight=5;
#server 127.0.0.1:1111 weight=5
}
# =====服务器级别=====
# if($slow){set $limit_rate 4k;} 限速
# log_not_found 默认on
# http|server|location.post_action uri 子请求
# http|server|location.resolver 指定dns解析服务器
server {
# 可以访问server的ip以及端口,一般只指定端口
listen 80;
# 1、主机名。2、。。。。
server_name localhost;
#charset koi8-r;
# 日志
access_log logs/host.access.log main;
# 本服务器的index
index index.html index.htm index.jsp;
# 资源根目录(动静分离)
root /usr/local/apache-tomcat-9/webapps/ROOT/;
# =====请求级别=====,匹配以(区分大小写) jpg|jpeg|gif|png|swf|ico结尾的
# (1)=表示uri.equals location = /abc
# (2)没有修饰符但是uri.equals location /abc
# (3)^~表示uri.startWith 如果匹配则停止搜索其他模式
# (4)~表示uri.match location ~ ^/abc$
# (4)~*表示uri.matchIgnoreCase location ~ ^/abc$
# (5)没有修饰符但是uri.startWith location /abc
location ~* .*\.(jpg|jpeg|gif|png|swf|ico)$ {
if (-f $request_filename) {
#expires 15d;
break;
}
}
location ~* .*\.(html|htm|js|css)$ {
#expires 1d;
}
# 代理到后端服务器 http://ydual.com 在上文upstream中有配置
location / {
proxy_pass http://ydual.com;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
# 指定 错误码 出现错误到哪个页面
error_page 500 502 503 504 /50x.html;
# internal或@xx 只支持内部访问 root表示追加,alias表示替换
location = /50x.html {
internal;
root errors/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
配置指令
Nginx 的行为由其主配置文件定义,该文件默认位于/usr/local/Nginx/conf/Nginx.conf。这个文件是由一个指令列表组成的。结构非常容易理解。比如
user root;
worker_processes 1;
error_log logs/error.log crit;
pid logs/nginx.pid;
events {
use epoll;
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
……
}
- 以“ # ”开头的行是注释
- Nginx 每个模块都有一套特定的指令。 当一个新模块被激活时,它的特定指令集变得可用。
- 某个块中找到的配置可以传递给它的子块。 但是,在子块中,您仍然可以更改在其父块中定义的值。
- include的最终结果为将 mime.types 的内容插入 nginx.conf 。然而,如果我们添加一个不存在的特定文件,Nginx 将无法正常启动
- 常见的配置文件有
- nginx.conf:应用程序的基本配置文件
- mime.types:MIME类型关联的扩展文件
- fastcgi.conf:与fastcgi相关的配置(PHP)
- proxy.conf:与proxy相关的配置
- sites.conf:配置Nginx提供的网站,包括虚拟主机
Nginx的内核
基本模块定义 Nginx 的基本参数和配置。在编译时内置到Nginx中。有三种类型的基本模块。。
core module
核心模块包含基本的指令和特性。 它的大多数指令必须放在配置文件的根目录(即顶部) 。
指令 | 语法和描述 |
---|---|
daemon | on / off 启用或禁用守护进程模式(在后台或前台启动程序) |
env | 语法:env MY_VARIABLE=my_value; 允许我们定义变量或定义环境变量 |
error_log | 可用于main, http, server,location 语法:error_log /path/to/file level 其中 level 可以是下列值之一: debug、 info、 notice、 warn、 error 和 crit 若要禁用错误日志记录,请将日志输出重定向到 / dev / null:error_log /dev/null crit; |
master_process | on / off 默认值:on Nginx 将同时启动主进程和辅助进程。 如果禁用,Nginx 将之启动一个进程。 这仅用于调试目的,并将导致客户端无法连接到服务器 |
pid | 语法:file path 存储 Nginx 的 PID 的文件的路径 |
user | 语法:user username groupname;或者user username; 允许您定义用于启动辅助进程的用户组(可选)。 出于安全原因,使用具有有限特权的用户 / 组 |
worker_processes | 语法:numeric or 或auto, for example: ,例如:worker_processes 4; 定义辅助进程的数量。 如果某个进程由于某种原因被阻塞,那么将来的请求可以由其他辅助进程来处理。 如果使用 auto 值,Nginx 将选择一个适当的值(默认情况下是检测到的 CPU 内核数量) |
worker_priority | worker_priority 0; 操作系统级别,辅助进程的优先级。从 -20(最高)到19(最低) |
event module
事件模块允许我们配置 Nginx 网络能力的操作。 这些指令必须放在配置文件根部的事件块中。
指令 | 语法和描述 |
---|---|
worker_connections | 定义辅助进程可以同时处理的连接数量 |
debug_connection | 语法: IP 地址或 CIDR 块,必须在调试级别启用,Nginx 必须使用–debug |
use | 语法 use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll(linux2.6的高性能方式 |
use epoll 的优点
段落引用支持一个进程打开大数目的socket描述符(FD)
IO效率不随FD数目增加而线性下降
使用mmap加速内核与用户空间的消息传递
内核微调
configuration module
配置模块允许文件包含在头文件中。该指令可以放置在配置文件的任何位置,并接受一个(且只接受一个)参数: 配置文件相对于当前工作目录的路径(也可以使用/指定相对于根路径)
HTTP 服务器
使用 HTTP Core 模块中的指令配置Web 服务器。 这个模块是 HTTP 配置的重要组成部分,它将允许我们——为多个网站提供服务,这些网站被称为虚拟主机。 它被组织成三个主要部分。
- http: 必须放置在配置文件的根目录下。 它的相关指令用于定义 web 服务器功能
- server: 必须配置在 http 块中,是用来声明一个特定的网站
- location: 允许我们定义网站的一组设置。该块既可以在server块中使用,也可以嵌套在另一个location块中
# http, server, location块
http{
include mime.types;
default_type application/octet-stream;
#access_log logs/access.log main;
sendfile on;
keepalive_timeout 65;
server{
listen 80;
server_name localhost;
root /home/gacanepa/nginx-1.5.6/html;
access_log /home/gacanepa/nginx-1.5.6/html/
location /restricted {
index index.html index.htm;
access_log off;
}
location / {
index index.html index.htm;
}
}
}
邮件服务器代理
要充当邮件服务器(默认情况下不启用) ,Nginx 必须使用 – with-mail (它支持 POP3、 IMAP4和 SMTP)选项编译。 / configure. 如果出于某种原因,这将是 Nginx 在我们的系统中的唯一用途,可以使用 – without-HTTP 交换机禁用 HTTP Core 模块。
我们可以看到邮件块的一部分,它用于设置邮件服务器的配置。 Imap、 pop3和 smtp 协议的功能以及详细的描述可以在 百度上找到。
mail{
server_name mail.gabrielcanepa.com.ar;
auth_http localhost:9000/auth.php;
imap_capabilities IMAP4rev1 UIDPLUS IDLE QUOTA+;
pop3_auth plain apop cram-md5;
pop3_capabilities LAST TOP USER PIPELINING UIDL;
stmp_auth login plain cram-md5;
stmp_capabilities "SIZE 10485760" ENHANCEDSTUSCODES 8BITMIME DNS;
server{
listen 25;
protocol stmp;
}
server{
listen 110;
protocol pop3;
proxy_pass_error_message on;
}
server{
listen 143;
……
}
}
虚拟主机
如前所述,虚拟主机是在服务器上由 Nginx 映射的网站。
第一步是在主配置文件中配置一个或多个server。 这些server可以通过主机名或通过组合或 IP:端口号来标识。
server {
listen 80;
server_name nginxtest.com;
root /home/gacanepa/nginx-1.5.6/html;
access_log /home/gacanepa/nginx-1.5.6/html/access_log;
location /restricted {
index index.html index.htm;
access_log off;
}
location / {
index index.html index.htm;
}
}
接下来,我们需要设置虚拟主机主配置文件。
Nginx 的默认安装提供了一个示例文件(位于 Nginx/sites-available/default) ,我们将在网站后复制该文件并为其命名:Nginx/sites-available/nginxtest.com
然后接下来要做的事情是编辑Nginx/sites-available/nginxtest.com文件
使用在 nginx.conf 文件基本相同的信息
启用虚拟主机现在必须在sites-enabled目录中创建该文件的软链接:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/nginxtest.com
为了避免冲突,我们还可以在启用站点的目录中删除名为 default 的文件:
sudo rm /etc/nginx/sites-enabled/default
最后让我们重新启动 Nginx.
Nginx 反向代理
同理,先上栗子
……
server {
listen 80;
server_name localhost;
access_log logs/host.access.log main;
index index.html index.htm index.jsp;
root /usr/local/apache-tomcat-9/webapps/ROOT/;
# 静态部分,如果图片在root目录中存在,则break;
location ~* .*\.(jpg|jpeg|gif|png|swf|ico)$ {
if (-f $request_filename) {
#expires 15d;
break;
}
}
# location中可以重写root的地址,便于配置多个项目的静态代理
location ~* .*\.(html|htm|js|css)$ {
#expires 1d;
}
# 动态部分走被代理服务器
location / {
proxy_pass http://ydual.com;
}
……
}
……
proxy.conf
#!nginx (-)
# proxy.conf
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; # 获取真实ip
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #获取代理者的真实ip
# 确认何种情况下请求将转发到下一个服务器
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
# Nginx没有读取到全部响应得情况下,写缓冲达到128k,Nginx会向客户端发送响应,直到缓冲小于此值。通常配置为proxy_buffers分页大小的倍数。
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 64k;
反向代理的概念
反向代理是放置在网络基础结构中的客户机和服务器之间的设备或服务。
图片来源:javaCodeGeeks
Nginx 将充当客户机(例如,您的计算机)和后端 web 服务器的反向代理
Nginx 的代理模块可以在后端对这些请求进行过滤或“交付”到 Apache服务器。
因为来自客户端的大量请求都是针对静态文件(html 页面、层叠样式表文件、常规图像等等) ,而 Nginx 提供静态文件的速度要快得多。
反代名称的由来
普通代理,用户local使用代理服务器访问目标服务器
反向代理,百度通过代理服务器管理目标服务器server1,server2,server3
Nginx代理模块
在安装 Nginx 期间,代理模块默认是启用的。代理模块可以转发请求到其他的服务器。
Nginx代理模块主要指令
指令 | 应用 | 描述 |
---|---|---|
proxy_pass | http server location |
被代理服务器的地址和被映射的URI或者unix.socket |
proxy_method | proxy_method POST 则后端服务器收到的永远是POST请求 | |
proxy_hide_header | http server location |
您可以指定要对客户机隐藏的附加标题行。例子:proxy_hide_header Cache-Control; |
proxy_pass_header | http server location |
强制将一些被忽略的标头传递给客户端。例子:proxy_pass_header Date; |
proxy_pass_request_body proxy_pass_request_headers |
http, server, location | 分别定义是否将请求正文和额外的请求头传递到后端服务器语法:on or off; |
proxy_redirect | http server location |
重定向,如果需要修改从被代理服务器传回的Location和Refresh字段。 proxy_redirect http://localhost:8080/ http://mysite.com/; |
代理缓存指令
指令 | 应用 | 描述 |
---|---|---|
proxy_buffering | http server location |
on | off 启用应答缓存 |
proxy_buffer_size | http server location |
设置从被代理服务器读取的第一部分应答的缓冲区大小,通常情况下这部分中包含一个小的应答头,默认情况下这个值得大小为指令proxy_buffers中指定得一个缓冲区大小,不过可以设置为更小 |
proxy_buffers | http server location |
设置用于读取应答(来自被代理服务器)缓冲区的数量和大小。 如果缓冲区不够大,数据将被保存到磁盘上,然后再提供给用户proxy_buffers 8 4k; |
proxy_cache_key | http server location |
缓存主键 proxy_cache_key “$scheme$host$request_uri$cookie_user”; |
proxy_cache | http server location |
开启网络访问加速,设置缓存区域名字。Nginx缓存不太完善,需要添加第三方模块ngx_cache_purge |
proxy_cache_path | http | 指定缓存路径 path [levels=levels] keys_zone=name:size [inactive=time] [max_size=size] [loader_files=number] [loader_sleep=time] [loader_threshold=time]; 如:proxy_cache_path /tmp/nginx_cache levels=1:2 zone=zone1:10m inactive=10m max_size=200M; |
proxy_cache_min_uses | http server location |
请求符合缓存条件之前的最小命中量 |
代理缓存指令扩展
指令 | 应用 | 描述 |
---|---|---|
proxy_connect_timeout | http server location |
定义后端服务器连接超时。 这不同于读 / 发送超时。这个超时时间通常不会超过75秒 |
proxy_read_timeout | http server location |
定义从代理服务器读取响应的超时。如果代理服务器在此时间内没有传输任何内容,则关闭连接,而不是整个传输响应的超时。默认60 |
proxy_send_timeout | http server location |
向后端服务器发送数据的超时时间。 同上。默认60 |
proxy_ignore_client_abort | http server location |
如果设置为 on,Nginx 将继续处理代理请求,即使客户端中止其请求。 在另一种情况下(off) ,当客户端中止它的请求时,Nginx 也中止它对后端服务器的请求,默认off |
proxy_max_temp_file_size | http server location if |
临时文件最大值默认1g,即后端服务器应答过大缓冲区溢出则写临时文件,临时文件满则改为同步传递请求 |
代理模块内置变量
参数 | 描述 |
---|---|
$proxy_host: | 被代理服务器的主机名 |
$proxy_port: | 被代理服务器端口 |
$proxy_add_x_forwarded_for: | 包含客户端请求头“ X-Forwarded-For” 如果没有 X-Forwarded-For 请求头,那么 $proxy add x forwarded for 等于 $remote addr |
$proxy_internal_body_length: | 内部body长度 |
负载均衡以及相关模块以及性能优化
Nginx是应用级别的负载均衡。能满足大部分的应用需求。默认使用轮询的方式分发请求。
负载均衡是一种将工作负载分布到多个计算资源网络(比如服务器、服务器集群(一组服务器以可以被视为单个系统的方式共同工作)、网络链接、 cpu 或其他硬件组件)的方法。 该技术旨在通过减少(或更准确地说是平衡)单个服务器或节点的负担来提高后端应用程序的容量(支持大量并发用户)和可靠性。负载平衡还提供了冗余和灾难恢复功能。
先上栗子
# geo模块。基于ip地理位置的分发
geo $geo{
default test1;
202.103.10.1/24 test2;
179.9.0.2/24 test3;
}
# 多个处理相同服务的服务器
upstream test1.server{
#server 127.0.00.1:9080 weight=5;
server 127.0.00.1:8080 weight=5;
#server 127.0.00.1:1111;
}
# weight权重,默认1。表示会被选择“n次”
# backup 备用服务器,不能和ip_hash一起使用
upstream test2.server{
#server 127.0.00.1:9080 weight=5;
server 127.0.00.1:8080 weight=5;
#server 127.0.00.1:1111 backup;
}
# 每30秒尝试3次重连。默认为每10s重连?次。
# down表示服务器挂了,必须和ip_hash一起使用
# 客户端的ip可能是不断变化的。并不能保证同一个ip总是访问同一个服务器
upstream test3.server{
ip_hash
#server 127.0.00.1:9080 weight=5 down;
server 127.0.00.1:8080 weight=5;
#server 127.0.00.1:1111 max_fails=3 fail_timeout=30s;
}
第三方负载均衡模块
// TODO 老师没讲过
Rewrite模块
用来执行URL重定向。有理由去掉恶意访问的url。有利于SEO。
捕获子表达式
就是正则表达式
^(.*)(hello|sir)$
if ($request_method = POST)
if ($http_cookie ~* "id=([^;] +)(?:;|)$"){set $_id $1}
if (-f $request_filename)
if (-d /usr/local/nginx)
if (-e /usr/local/sbin/nginx)
if (-x /usr/local/nginx/sbin/nginx)
# 其他
if ($invalid_referer){return 403;}
if ($args ~ post=140){rewrite}
// TODO 完结撒花
其他模块
# index 设置一个默认主页
# Referer 防盗链
referer none blocked server_name
# $binary_remote_addr每个ip会话状态最多10m
limit_zone zone_name $binary_remote_addr 10m
# 限制一个会话的最大连接数
limit_conn zone_name 1;
limit_conn_log_level info | notice | warn | error
error_page 403 http://ydual.com/forbidden.html
location /{
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
deny all;
}
# 重写response的content-type
charset windows-1251;
gzip on;
gzip_buffers 4 16k;
# 1-9压缩等级1最快9最小
gzip_comp_level 2;
gzip_min_length 1000;
# 是否启用代理请求压缩
gzip_proxied expired no-cache no-store private auto any
gzip_types text/plain application/xml;
gzip_disable "MSIE [1-6]\.";
# 安装openssl
yum install libssl-dev
# 启用ssh支持,不能本地生成好了再安装?
./configure --with-http_ssl_module
mkdir /usr/local/nginx/ssl
openssl genrsa -out server.key 1024
openssl req -new -key server.key -out server.csr -config /etc/ssl/openssl.cnf
# 证书上签名
openssl x509 -req -days 1 -in server.csr -signkey server.key -out server.crt -extensions v3_req -extfile /etc/ssl/openssl.cnf
server{
listen 443 ssl;
.....
ssl_certificate /usr/local/nginx/ssl/server.crt;
ssl_certificate_key /usr/local/nginx/ssl/server.key;
location /{
index index.html index.htm;
}
}
优化建议
- 需要结合实际测试数据来优化
- 优化单台机器效率,降低负载,降低磁盘/网络I/O,降低内存使用,高效利用cpu
- Nginx模块最小化
- 创建用户和组 user nginx nginx
- worker_process 配置成cpu总和或者其2倍
- worker_cpu_affinity绑定cpu,使得每个worker进程独享一个cpu
- events,linux用 epoll,FreeBSD使用kqueue
- worker_rlimit_noffile 改大,改大内核最大打开文件数 /etc/security/limits.conf
- worker_connections 依据理论并发加大
- keepalive_timeout 设置65左右
- client_header_buffer_size 最大可设置为系统分页大小(getconf PAGESIZE)整数倍
- open_file_cache max=建议内核最大文件数 inactive=60s
- open_file_cache_valid 90s;
- open_file_cache_min_uses 2;
- open_file_cache_errors on;
- 尽量开启gzip,更具cpu配置3~5
- error日志设置crit,减少I/O
- access日志优化,根据需要可以关闭或输出到内存,提高I/O效率
- sendfile 如果不是下载等磁盘I/O负载应用需要设置为 on
- buffers size 优化,client_body_buffer_size 需要足以容纳上传的POST数据,后端buffer。较少磁盘I/O
- worker_priority 通常 [-20 +19] 设置为-1 大于内核优先级 -5
- expires 1d 启用浏览器缓冲
- accept_mutex 建议开启
- 使用SSL尽量开启SSL硬件加速
- 单台Nginx和单台Tomcat性能反而下降了,多了一层代理。