您的位置:首页 > 运维架构 > Nginx

nginx基本配置与参数说明

2017-03-11 22:21 555 查看
#定义Nginx运行的用户和用户组

user www www;

#nginx进程数,建议设置为等于CPU总核心数。

worker_processes 8;

#全局错误日志定义类型,[ debug | info | notice | warn | error | crit ]

error_log /var/log/nginx/error.log info;

#进程文件

pid /var/run/nginx.pid;

#一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(系统的值ulimit -n)与nginx进程数相除,但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致。

worker_rlimit_nofile 65535;

#工作模式与连接数上限

events

{

#参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。

use epoll;

#单个进程最大连接数(最大连接数=连接数*进程数)

worker_connections 65535;

}

#设定http服务器

http

{

include mime.types; #文件扩展名与文件类型映射表

default_type application/octet-stream; #默认文件类型

#charset utf-8; #默认编码

server_names_hash_bucket_size 128; #服务器名字的hash表大小

client_header_buffer_size 32k; #上传文件大小限制

large_client_header_buffers 4 64k; #设定请求缓

client_max_body_size 8m; #设定请求缓

sendfile on; #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。

autoindex on; #开启目录列表访问,合适下载服务器,默认关闭。

tcp_nopush on; #防止网络阻塞

tcp_nodelay on; #防止网络阻塞

keepalive_timeout 120; #长连接超时时间,单位是秒

#FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。下面参数看字面意思都能理解。

fastcgi_connect_timeout 300;

fastcgi_send_timeout 300;

fastcgi_read_timeout 300;

fastcgi_buffer_size 64k;

fastcgi_buffers 4 64k;

fastcgi_busy_buffers_size 128k;

fastcgi_temp_file_write_size 128k;

#gzip模块设置

gzip on; #开启gzip压缩输出

gzip_min_length 1k; #最小压缩文件大小

gzip_buffers 4 16k; #压缩缓冲区

gzip_http_version 1.0; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)

gzip_comp_level 2; #压缩等级

gzip_types text/plain application/x-javascript text/css application/xml;

#压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。

gzip_vary on;

#limit_zone crawler $binary_remote_addr 10m; #开启限制IP连接数的时候需要使用

limit_req_zone $binary_remote_addr zone=allips:10m rate=10r/m; #同一时间IP访问限制 防止DDOS攻击

limit_conn_zone $binary_remote_addr zone=limitConn:10m; #限制并发连接数

upstream blog.ha97.com {

#upstream的负载均衡,weight是权重,可以根据机器配置定义权重。weigth参数表示权值,权值越高被分配到的几率越大。

server 192.168.80.121:80 weight=3;

server 192.168.80.122:80 weight=2;

server 192.168.80.123:80 weight=3;

}

#虚拟主机的配置



server

{

#监听端口

listen 80;

#域名可以有多个,用空格隔开

server_name www.ha97.com ha97.com;

index index.html index.htm index.php;

root /data/www/ha97;

location ~ .*\.(php|php5)?$

{

fastcgi_pass 127.0.0.1:9000;

fastcgi_index index.php;

include fastcgi.conf;

}

#图片缓存时间设置

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$

{

expires 10d;

}

#JS和CSS缓存时间设置

location ~ .*\.(js|css)?$

{

expires 1h;

}

#日志格式设定

log_format access '$remote_addr - $remote_user [$time_local] "$request" '

'$status $body_bytes_sent "$http_referer" '

'"$http_user_agent" $http_x_forwarded_for';

#定义本虚拟主机的访问日志

access_log /var/log/nginx/ha97access.log access;

#对 "/" 启用反向代理

location / {

proxy_pass http://127.0.0.1:88;
proxy_redirect off;

proxy_set_header X-Real-IP $remote_addr;

#后端的Web服务器可以通过X-Forwarded-For获取用户真实IP

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

#以下是一些反向代理的配置,可选。

proxy_set_header Host $host;

client_max_body_size 10m; #允许客户端请求的最大单文件字节数

client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,

proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)

proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)

proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)

proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小

proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的设置

proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2)

proxy_temp_file_write_size 64k;

#设定缓存文件夹大小,大于这个值,将从upstream服务器传

}

#设定查看Nginx状态的地址

location /NginxStatus {

stub_status on;

access_log on;

auth_basic "NginxStatus";

auth_basic_user_file conf/htpasswd;

#htpasswd文件的内容可以用apache提供的htpasswd工具来产生。

}

#本地动静分离反向代理配置

#所有jsp的页面均交由tomcat或resin处理

location ~ .(jsp|jspx|do)?$ {

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_pass http://127.0.0.1:8080;
}

#所有静态文件由nginx直接读取不经过tomcat或resin

location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$

{ expires 15d; }

location ~ .*.(js|css)?$

{ expires 1h; }

}

}

nginx 负载均衡proxy 配置

在http模块 加入

upstream fuzai{

server 服务器ip; #有端口的话 ip:端口 默认80端口可以不写

}

在server 模块需要负载的location加入

location / {

proxy_pass http://fuzai;
proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

}

配置nginx的rewrite

这个模块就是安装的时候用的pcre软件提供的

rewrite指定语法; rewrite regex replacement[flag] 应用位置 server、location 、if

该指令根据表达式来重定向URI,或者修改字符串。指令根据配置文件中的顺序来执行。注意重写表达式只对相对路径有效。如果你想配对主机名,你应该使用if语句,示例如下:

先说后面的flag 的几个说明吧:

1.last 相当于apache里面的[L]标记,表示rewrite。

2.break本条规则匹配完成后,终止匹配,不再匹配后面的规则。

3.redirect 返回302临时重定向,浏览器地址会显示跳转后的URL地址。

4.permanent 返回301永久重定向, 浏览器地址会显示跳转后的URL地址

例子: rewrite ^/(.*) http://www.daxia.help/$1 permanent; #rewrite是关键字 regex部分^/(.*) 这是一个正则表达式,表示匹配所以,匹配成功后跳转到后面的 replacement部分也就是www.daxia.help这个域名 $1是引用前面()里面的内容简化写入的,permanent是301永久跳转,这是告诉搜索引擎的。

log_format 是定义日志格式的关键字

main是标签 remote_addr 是记录访问客户端的地址

remote_user 远程访问客户端的名称

time_local是日期

request 是http起始行的信息

status http的状态码 200 404 等

body-bytes_set 是服务器发送给客户端的响应body字节数

http_referer 记录这次访问是从那个链接访问过来的用于防盗链设置

http_user_agent 是记录浏览器的信息 比如是手机还是谷歌浏览器 360浏览器等 http_x_forwarded_for 当有代理时候设置这个记录客户端的真实地址用的

access_log 配置 语法: access_log path[format[buffer=size[flush=time]] [if=condition]; access_log path format gzip [=level] [buffer=size][flush=time][if=condition] ; access_log syslog:server=address[ paarmeter=value][format[if=condition]];

buffer=size 是存放访问日志的缓冲区大小,flush=time是日志多久刷新到硬盘的时间 ,gzip[level] 表示压缩级别 [if=condition] 表示其他条件 一般这些都不需要配置

access_log off 是关闭记录日志 可以应用到 http server location \if in locaton\limit_except中

例子: access_log logs/access_www.log main gzip buffer=32k flush=5s;

location的配置

nginx location语法

基本语法:location [=|~|~*|^~] /uri/ { … }

= 严格匹配。如果这个查询匹配,那么将停止搜索并立即处理此请求。

~ 为区分大小写匹配(可用正则表达式)

~* 为不区分大小写匹配(可用正则表达式)

!~和!~*分别为区分大小写不匹配及不区分大小写不匹配

^~ 如果把这个前缀用于一个常规字符串,那么告诉nginx 如果路径匹配那么不测试正则表达式。

Nginx 允许用户定义 Location block ,并指定一个匹配模式(pattern)匹配特定的 URI。除了简单的字符串(比如文件系统路径),还允许使用更为复杂的匹配模式(pattern)。

Location block 的基本语法形式是:

location [=|~|~*|^~|@] pattern { ... }

[=|~|~*|^~|@] 被称作 location modifier ,这会定义 Nginx 如何去匹配其后的 pattern ,以及该 pattern 的最基本的属性(简单字符串或正则表达式)。

------- 关于 location modifier -------

1. =

这会完全匹配指定的 pattern ,且这里的 pattern 被限制成简单的字符串,也就是说这里不能使用正则表达式。

Example:

server {

server_name website.com;

location = /abcd {

[…]

}

}

匹配情况:
http://website.com/abcd # 正好完全匹配
http://website.com/ABCD # 如果运行 Nginx server 的系统本身对大小写不敏感,比如 Windows ,那么也匹配
http://website.com/abcd?param1m2 # 忽略查询串参数(query string arguments),这里就是 /abcd 后面的 ?param1m2
http://website.com/abcd/ # 不匹配,因为末尾存在反斜杠(trailing slash),Nginx 不认为这种情况是完全匹配
http://website.com/abcde # 不匹配,因为不是完全匹配

2. (None)

可以不写 location modifier ,Nginx 仍然能去匹配 pattern 。这种情况下,匹配那些以指定的 patern 开头的 URI,注意这里的 URI 只能是普通字符串,不能使用正则表达式。

Example:

server {

server_name website.com;

location /abcd {

[…]

}

}

匹配情况:
http://website.com/abcd # 正好完全匹配
http://website.com/ABCD # 如果运行 Nginx server 的系统本身对大小写不敏感,比如 Windows ,那么也匹配
http://website.com/abcd?param1m2 # 忽略查询串参数(query string arguments),这里就是 /abcd 后面的 ?param1m2
http://website.com/abcd/ # 末尾存在反斜杠(trailing slash)也属于匹配范围内
http://website.com/abcde # 仍然匹配,因为 URI 是以 pattern 开头的

3. ~

这个 location modifier 对大小写敏感,且 pattern 须是正则表达式

Example:

server {

server_name website.com;

location ~ ^/abcd$ {

[…]

}

}

匹配情况:
http://website.com/abcd # 完全匹配
http://website.com/ABCD # 不匹配,~ 对大小写是敏感的
http://website.com/abcd?param1m2 # 忽略查询串参数(query string arguments),这里就是 /abcd 后面的 ?param1m2
http://website.com/abcd/ # 不匹配,因为末尾存在反斜杠(trailing slash),并不匹配正则表达式 ^/abcd$
http://website.com/abcde # 不匹配正则表达式 ^/abcd$

注意:对于一些对大小写不敏感的系统,比如 Windows ,~ 和 ~* 都是不起作用的,这主要是操作系统的原因。

4. ~*

与 ~ 类似,但这个 location modifier 不区分大小写,pattern 须是正则表达式

Example:

server {

server_name website.com;

location ~* ^/abcd$ {

[…]

}

}

匹配情况:
http://website.com/abcd # 完全匹配
http://website.com/ABCD # 匹配,这就是它不区分大小写的特性
http://website.com/abcd?param1m2 # 忽略查询串参数(query string arguments),这里就是 /abcd 后面的 ?param1m2
http://website.com/abcd/ # 不匹配,因为末尾存在反斜杠(trailing slash),并不匹配正则表达式 ^/abcd$
http://website.com/abcde # 不匹配正则表达式 ^/abcd$

5. ^~

匹配情况类似 2. (None) 的情况,以指定匹配模式开头的 URI 被匹配,不同的是,一旦匹配成功,那么 Nginx 就停止去寻找其他的 Location 块进行匹配了(与 Location 匹配顺序有关)

6. @

用于定义一个 Location 块,且该块不能被外部 Client 所访问,只能被 Nginx 内部配置指令所访问,比如 try_files or error_page

------- 搜索顺序以及生效优先级 -------

因为可以定义多个 Location 块,每个 Location 块可以有各自的 pattern 。因此就需要明白(不管是 Nginx 还是你),当 Nginx 收到一个请求时,它是如何去匹配 URI 并找到合适的 Location 的。

要注意的是,写在配置文件中每个 Server 块中的 Location 块的次序是不重要的,Nginx 会按 location modifier 的优先级来依次用 URI 去匹配 pattern ,顺序如下:

1. =

2. (None) 如果 pattern 完全匹配 URI(不是只匹配 URI 的头部)

3. ^~

4. ~ 或 ~*

5. (None) pattern 匹配 URI 的头部

7.匹配案例

location = / {

# 精确匹配 / ,主机名后面不能带任何字符串

[ configuration A ]

}

location / {

# 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求

# 但是正则和最长字符串会优先匹配

[ configuration B ]

}

location /documents/ {

# 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索

# 只有后面的正则表达式没有匹配到时,这一条才会采用这一条

[ configuration C ]

}

location ~ /documents/Abc {

# 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索

# 只有后面的正则表达式没有匹配到时,这一条才会采用这一条

[ configuration CC ]

}

location ^~ /images/ {

# 匹配任何以 /images/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条。

[ configuration D ]

}

location ~* \.(gif|jpg|jpeg)$ {

# 匹配所有以 gif,jpg或jpeg 结尾的请求

# 然而,所有请求 /images/ 下的图片会被 config D 处理,因为 ^~ 到达不了这一条正则

[ configuration E ]

}

location /images/ {

# 字符匹配到 /images/,继续往下,会发现 ^~ 存在

[ configuration F ]

}

location /images/abc {

# 最长字符匹配到 /images/abc,继续往下,会发现 ^~ 存在

# F与G的放置顺序是没有关系的

[ configuration G ]

}

location ~ /images/abc/ {

# 只有去掉 config D 才有效:先最长匹配 config G 开头的地址,继续往下搜索,匹配到这一条正则,采用

[ configuration H ]

}

location ~* /js/.*/\.js

顺序 no优先级:

(location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (/)

上面的匹配结果

按照上面的location写法,以下的匹配示例成立:

/ -> config A

精确完全匹配,即使/index.html也匹配不了

/downloads/download.html -> config B

匹配B以后,往下没有任何匹配,采用B

/images/1.gif -> configuration D

匹配到F,往下匹配到D,停止往下

/images/abc/def -> config D

最长匹配到G,往下匹配D,停止往下

你可以看到 任何以/images/开头的都会匹配到D并停止,FG写在这里是没有任何意义的,H是永远轮不到的,这里只是为了说明匹配顺序

/documents/document.html -> config C

匹配到C,往下没有任何匹配,采用C

/documents/1.jpg -> configuration E

匹配到C,往下正则匹配到E

/documents/Abc.jpg -> config CC

最长匹配到C,往下正则顺序匹配到CC,不会往下到E

8.实际使用建议

所以实际使用中,个人觉得至少有三个匹配规则定义,如下:

#直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说。

#这里是直接转发给后端应用服务器了,也可以是一个静态首页

# 第一个必选规则

location = / {

proxy_pass http://tomcat:8080/index
}

# 第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项

# 有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用

location ^~ /static/ {

root /webroot/static/;

}

location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {

root /webroot/res/;

}

#第三个规则就是通用规则,用来转发动态请求到后端应用服务器

#非静态文件请求就默认是动态请求,自己根据实际把握

location / {

proxy_pass http://tomcat:8080/
}

nginx配置https网站

前提:

1、主机要先安装openssl

2、编译安装nginx时,要加上--with-openssl和--with-http_ssl_module

1、生成自签字证书

[root@101 /]# openssl req -new -x509 -keyout /root/ca.key -out /root/ca.crt

Generating a 2048 bit RSA private key

.............+++

...................................+++

writing new private key to '/root/ca.key'

Enter PEM pass phrase: #输入密钥保护密码

Verifying - Enter PEM pass phrase: #确认密码保护密码

-----

You are about to be asked to enter information that will be incorporated

into your certificate request.

What you are about to enter is what is called a Distinguished Name or a DN.

There are quite a few fields but you can leave some blank

For some fields there will be a default value,

If you enter '.', the field will be left blank.

-----

Country Name (2 letter code) [XX]:CN

State or Province Name (full name) []:guangzhou

Locality Name (eg, city) [Default City]:guangzhou

Organization Name (eg, company) [Default Company Ltd]:lzs

Organizational Unit Name (eg, section) []:it

Common Name (eg, your name or your server's hostname) []:101.lzs.com

Email Address []:root@lzs.com

2、修改配置文件openssl.cnf

vim /etc/pki/tls/openssl.cnf

[ ca ]

default_ca = CA_default # The default ca section

####################################################################

[ CA_default ]

dir = /etc/pki/CA #证书的根目录,要记住这个目录

certs = $dir/certs

crl_dir = $dir/crl

database = $dir/index.txt

#unique_subject = no

new_certs_dir = $dir/newcerts

certificate = $dir/ca.crt # 修改这里,表示签名时使用的证书

serial = $dir/serial

crlnumber = $dir/crlnumber

crl = $dir/crl.pem

private_key = $dir/private/cakey.pem

RANDFILE = $dir/private/.rand

3、复制证书到证书根目录/etc/pki/CA下,并在该目录下创建空文件index.txt和serial,并向serial输入”01“

cd /etc/pki/CA

cp /root/ca.crt .

touch index.txt

touch serial

echo "01" >serial

4、生成服务器RSA私钥/root/server.key

openssl genrsa -des3 -out /root/server.key 1024

5、为私钥去除口令

openssl rsa -in /root/server.key -out /root/server_nopwd.key

5、生成证书请求文件/root/server.csr

[root@101 /]# openssl req -new -key /root/server.key -out /root/server.csr

Enter pass phrase for /root/server.key: #输入第4步生成的密钥的保护密码

You are about to be asked to enter information that will be incorporated

into your certificate request.

What you are about to enter is what is called a Distinguished Name or a DN.

There are quite a few fields but you can leave some blank

For some fields there will be a default value,

If you enter '.', the field will be left blank.

--------下面这部分应该和创建私有证书时填的一样------------------------

Country Name (2 letter code) [XX]:CN

State or Province Name (full name) []:guangzhou

Locality Name (eg, city) [Default City]:guangzhou

Organization Name (eg, company) [Default Company Ltd]:lzs

Organizational Unit Name (eg, section) []:it

Common Name (eg, your name or your server's hostname) []:101.lzs.com

----------------------------------------------------------------

Email Address []:root@lzs.com

Please enter the following 'extra' attributes

to be sent with your certificate request

A challenge password []:www.lzs.com

An optional company name []:lzs

6、用私有证书给证书请求文件/root/server.csr签名

[root@101 CA]# openssl ca -in /root/server.csr -out /root/server.crt -cert /root/ca.crt -keyfile /root/ca.key -config /etc/pki/tls/openssl.cnf

Using configuration from /etc/pki/tls/openssl.cnf

Enter pass phrase for ca.key:

Check that the request matches the signature

Signature ok

Certificate Details:

Serial Number: 1 (0x1)

Validity

Not Before: Aug 31 14:09:15 2016 GMT

Not After : Aug 31 14:09:15 2017 GMT

Subject:

countryName = CN

stateOrProvinceName = guangzhou

organizationName = lzs

organizationalUnitName = it

commonName = 101.lzs.com

emailAddress = root@lzs.com

X509v3 extensions:

X509v3 Basic Constraints:

CA:FALSE

Netscape Comment:

OpenSSL Generated Certificate

X509v3 Subject Key Identifier:

18:80:30:B7:C6:11:61:AE:F3:62:9D:D0:33:D9:97:CB:45:5A:31:91

X509v3 Authority Key Identifier:

keyid:DA:99:4B:9B:29:A8:D8:14:54:FA:52:4B:1E:C3:E0:81:C6:A6:EF:42

Certificate is to be certified until Aug 31 14:09:15 2017 GMT (365 days)

Sign the certificate? [y/n]:yes

1 out of 1 certificate requests certified, commit? [y/n]y

Write out database with 1 new entries

Data Base Updated

7、编辑nginx配置文件/etc/nginx/nginx.conf



-------在配置文件的特定区域加入/修改下面内容

server {

listen 443 ssl; #设置监听的端口

server_name lzs;

ssl on;

ssl_certificate /root/server.crt;

ssl_certificate_key /root/server_nopwd.key;

8、重启服务
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: