46.3. nginx 配置文件

worker_processes = CPU 数量

user  www;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
	

46.3.1. http 配置

自定义缓冲区相关设置

client_body_buffer_size  1K;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
		

超时相关设置

client_body_timeout   10;
client_header_timeout 10;
keepalive_timeout  	  65;
send_timeout          10;
		

46.3.2. events

events {
    worker_connections  4096;
}
		

46.3.3. gzip

gzip  on;
gzip_min_length  1000;
gzip_buffers     4 8k;
gzip_types       text/plain text/css application/json application/x-javascript application/xml;

gzip on;
gzip_http_version 1.0;
gzip_disable "MSIE [1-6].";
gzip_types text/plain application/x-javascript text/css text/javascript;
			

gzip_types 压缩类型

gzip_types text/plain text/css application/javascript text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
			

text/html 是 gzip_types 默认值,所以不要将text/html加入到gzip_types

测试,验证 gzip 正常工作

neo@netkiller:~/workspace$ curl -s -I -H 'Accept-Encoding: gzip,deflate' http://img.netkiller.cn/js/react.js | grep gzip
Content-Encoding: gzip
			

如果提示 Content-Encoding: gzip 便是配置正确

不仅仅只能压缩html,js,css还能压缩json

neo@netkiller:~$ curl -s -I -H 'Accept-Encoding: gzip,deflate' http://inf.netkiller.cn/list/json/2.json
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 15 Dec 2016 03:36:31 GMT
Content-Type: application/json; charset=utf-8
Connection: keep-alive
Cache-Control: max-age=60
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type,Origin
Access-Control-Allow-Methods: GET,OPTIONS
Content-Encoding: gzip
			

46.3.3.1. CDN支持

配置 gzip_proxied any; 后CDN才能识别 gzip

	server_tokens off;
    gzip  on;
    gzip_types text/plain text/css application/javascript text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
    gzip_proxied any;
			

46.3.4. server_tokens

隐藏nginx版本号

http {
...
server_tokens off;
...
}
			

46.3.5. ssi

http {
  ssi  on;
}

location / {
  ssi on;
  ssi_silent_errors on;
  ssi_types text/shtml;
}
		
ssi on;
ssi_silent_errors on;
ssi_types text/shtml;
ssi_value_length 256;
server_names_hash_bucket_size 128;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 8m;
			

ssi_silent_errors 默认值是off,开启后在处理SSI文件出错时不输出错误提示:"[an error occurred while processing the directive] "

ssi_types 默认是ssi_types text/html,如果需要shtml支持,则需要设置:ssi_types text/shtml

ssi_value_length 默认值是 256,用于定义SSI参数的长度。

46.3.6. server

46.3.6.1. listen

绑定IP地址

listen 80; 相当于0.0.0.0:80监听所有接口上的IP地址
listen 192.168.0.1 80;
listen 192.168.0.1:80;
			

配置默认主机 default_server

server {
    listen       80;
    server_name  acc.example.net;
    ...
}

server {
    listen       80  default_server;
    server_name  www.example.org;
    ...
}
			

46.3.6.2. 单域名虚拟主机

# cat /etc/nginx/conf.d/images.conf
server {
    listen       80;
    server_name  images.example.com;

    #charset koi8-r;
    access_log  /var/log/nginx/images.access.log  main;

    location / {
        root   /www/images;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/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;
    #}
}
			

绑定多个域名

server_name  images.example.com img1.example.com img2.example.com;
			

使用通配符匹配

server_name  *.example.com
server_name  www.*;
			

正则匹配

server_name ~^(.+)\.example\.com$;
server_name ~^(www\.)?(.+)$;
			

46.3.6.3. ssl 虚拟主机

mkdir /etc/nginx/ssl
			

cp your_ssl_certificate to /etc/nginx/ssl

# HTTPS server
#
server {
	listen 443;
	server_name localhost;

	root html;
	index index.html index.htm;

	ssl on;
	#ssl_certificate cert.pem;
	ssl_certificate ssl/example.com.pem;
	ssl_certificate_key ssl/example.com.key;

	ssl_session_timeout 5m;

	ssl_protocols SSLv3 TLSv1;
	ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;
	ssl_prefer_server_ciphers on;

	location / {
		try_files $uri $uri/ /index.html;
	}
}
			

configtest

$ sudo service nginx configtest
Testing nginx configuration: nginx.
			

443 port test

$ openssl s_client -connect www.example.com:443
			

46.3.6.4. server_name 配置

匹配所有域名

server_name  _;
			

泛解析主机

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

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

server {
    listen       80;
    server_name  mail.*;
    ...
}

server {
    listen       80;
    server_name  ~^(?<user>.+)\.example\.net$;
    ...
}			

46.3.6.5. root 通过$host智能匹配目录

为每个host创建一个目录太麻烦,

server {
    listen       80;
    server_name www.netkiller.cn news.netkiller.cn bbs.netkiller.cn;

    charset utf-8;
    access_log  /var/log/nginx/test.access.log  main;

    location / {
        root   /www/netkiller.cn/$host;
        index  index.html index.htm;
    }
}
			

处理主机名中的域

server {
	listen       80;
	server_name  *.example.com example.com;
	if ($host = 'example.com' ) {
		rewrite ^/(.*)$ http://www.example.com/$1 permanent;
	}

	if ( $host ~* (.*)\.(.*)\.(.*)) {
		set $subdomain $1;
		set $domain $2.$3;
	}

	root  /www/$domain/$subdomain;
	index index.html index.php;

	location ~ .*\.(php|shtml)?$ {
		fastcgi_pass  127.0.0.1:9000;
		fastcgi_index index.php;
		include fcgi.conf;
	}
}
			

或者采用这种格式 /www/example.com/www.example.com

root  /www/$domain/$host;
			

更简洁的方法,只需在 /www/下面创建 域名目录即可例如/www/www.example.com

server {
	listen       80;
	server_name  *.example.com example.com;
	if ($host = 'example.com' ) {
		rewrite ^/(.*)$ http://www.example.com/$1 permanent;
	}

	root  /www/$host;
	index index.html index.php;

	location ~ .*\.(php|shtml)?$ {
		fastcgi_pass  127.0.0.1:9000;
		fastcgi_index index.php;
		include fcgi.conf;
	}
}
			

46.3.6.6. location

    location / {
        root   /www;
        index  index.html index.htm;
    }
			
    location ~ ^/(config|include)/ {
        deny all;
        break;
    }
			

引用document_root之外的资源

    location / {
		root /www/example.com/m.example.com;
		try_files $uri $uri/ @proxy;
    }
    location ^~ /module/ {
        root /www/example.com/www.example.com;
    }

    # 下面的写法是错误的,通过error_log 我们可以看到被定为到/www/example.com/m.example.com/module
	location /module/ {
    	root /www/example.com/www.example.com;
	}
			

46.3.6.7. expires

expires 格式

例 46.1. Expires Examples

expires 1 January, 1970, 00:00:01 GMT;
expires 60s;
expires 30m;
expires 24h;
expires 1d;
expires max;
expires off;

expires       24h;
expires       modified +24h;
expires       @15h30m;
expires       0;
expires       -1;
expires       epoch;
add_header    Cache-Control  private;
				

注意:expires仅仅适用于200, 204, 301, 302,304

单个文件匹配

    location ~* \.css$ {
       expires 30d;
    }
			

扩展名匹配

#图片类资源缓存5天,并且不记录请求日志
location ~ .*\.(ico|gif|jpg|jpeg|png|bmp|swf)$
{
        expires      5d;
        access_log off;
}

#css/js 缓存一天,不记录请求日志
location ~ .*\.(js|css)$
{
        access_log off;
        expires      1d;
        add_header Pragma public;
        add_header Cache-Control "public";
}
			
location ~ .*\.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
{
    expires      30d;
}
location ~ .*\.(js|css)$
{
    expires      1h;
}
			
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
	if (-f $request_filename) {
	   expires    1h;
	   break;
	}
}

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

#cache control: all statics are cacheable for 24 hours
location / {
        if ($request_uri ~* \.(ico|css|js|gif|jpe?g|png)$) {
                expires 72h;
                break;
        }
}
			

例 46.2. nginx expires

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
    expires      1d;
    access_log   off;
}

location ~ .*\.(js|css)$ {
    expires      1d;
    access_log   off;
}
location ~ .*\.(html|htm)$
{
    expires      1d;
    access_log off;
}
				
46.3.6.7.1. 通过 add_header / more_set_headers 设置缓存

add_header 实例

location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
    expires 30d;
    add_header Pragma public;
    add_header Cache-Control "public";
}
				

more_set_headers 实例

location ~ \.(ico|pdf|flv|jp?g|png|gif|js|css|webp|swf)(\.gz)?(\?.*)?$ {
           more_set_headers 'Cache-Control: max-age=86400';
           ...
           proxy_cache_valid 200 2592000;
           ...
}
				

s-maxage 作用于 Proxy

location ~ \.(ico|pdf|flv|jp?g|png|gif|js|css|webp|swf)(\.gz)?(\?.*)?$ {
           more_set_headers 'Cache-Control: s-maxage=86400';
}
				
46.3.6.7.2. $request_uri
if ($request_uri ~* "\.(ico|css|js|gif|jpe?g|png)\?[0-9]+$") {
    expires max;
    break;
}
				

下面例子是缓存 /detail/html/5/4/321035.html, 但排除 /detail/html/5/4/0.html

if ($request_uri ~ ^/detail/html/[0-9]+/[0-9]/[^0][0-9]+\.html ) {
    expires 1d;
}
				
46.3.6.7.3. $request_filename
if (-f $request_filename) {
     expires 1d;
}
				

46.3.6.8. access

#防止access文件被下载
location ~ /\.ht {
    deny  all;
}
			
location ~ ^/upload/.*\.php$
{
        deny all;
}

location ~ ^/static/images/.*\.php$
{
        deny all;
}
			
location ~ /\.ht {
    deny all;
}

location ~ .*\.(sqlite|sq3)$ {
    deny all;
}
			

IP 地址

location / {
	deny  192.168.0.1;
	allow 192.168.1.0/24;
	allow 10.1.1.0/16;
	allow 2001:0db8::/32;
	deny  all;
}
			

限制IP访问*.php文件

location ~ ^/private/.*\.php$
{
    allow   222.222.22.35;
    allow   192.168.1.0/249;
    deny    all;
}
			

46.3.6.9. autoindex

开启目录浏览

# vim /etc/nginx/sites-enabled/default

location  /  {
  autoindex  on;
}
			
# /etc/init.d/nginx reload
Reloading nginx configuration: nginx.
			

46.3.6.10. try_files

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

    location / {
        try_files $uri $uri/ /index.php?/$request_uri;
    }

    location /example {
        alias /www/example/;
        index index.php index.html;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    location ~ \.php$ {
        root           html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /www/example$fastcgi_script_name;
        include        fastcgi_params;
    }

    location ~ /\.ht {
        deny  all;
    }
}
			

46.3.6.11. add_header

# 相关页面设置Cache-Control头信息

      if ($request_uri ~* "^/$|^/news/.+/|^/info/.+/") {
        add_header    Cache-Control  max-age=3600;
      }

      if ($request_uri ~* "^/suggest/|^/categories/") {
        add_header    Cache-Control  max-age=86400;
      }
			
46.3.6.11.1. Cache
add_header     Nginx-Cache     "HIT  from  www.example.com";
or
add_header     Nginx-Cache     "$upstream_cache_status  from  www.example.com";
46.3.6.11.2. Access-Control-Allow
location ~* \.(eot|ttf|woff)$ {
    add_header Access-Control-Allow-Origin *;
}

location /js/ {
add_header Access-Control-Allow-Origin https://www.mydomain.com/;
add_header Access-Control-Allow-Methods GET,OPTIONS;
add_header Access-Control-Allow-Headers *;
}
				
location / {
    if ($request_method = OPTIONS ) {
        add_header Access-Control-Allow-Origin "http://example.com";
        add_header Access-Control-Allow-Methods "GET, OPTIONS";
        add_header Access-Control-Allow-Headers "Authorization";
        add_header Access-Control-Allow-Credentials "true";
        add_header Content-Length 0;
        add_header Content-Type text/plain;
        return 200;
    }
}
				

46.3.7. HTTP2 配置 SSL证书

46.3.7.1. 自颁发证书

创建自颁发证书,SSL有两种证书模式,单向认证和双向认证,下面是单向认证模式。

mkdir /etc/nginx/ssl
cd /etc/nginx/ssl
openssl req -x509 -nodes -days 365 -newkey rsa:4096 -keyout /etc/nginx/ssl/api.netkiller.cn.key -out /etc/nginx/ssl/api.netkiller.cn.crt

Generating a 4096 bit RSA private key
..........++
..............................................++
writing new private key to '/etc/nginx/ssl/api.netkiller.cn.key'
-----
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) []:Guangdong
Locality Name (eg, city) [Default City]:Shenzhen
Organization Name (eg, company) [Default Company Ltd]:CF
Organizational Unit Name (eg, section) []:CF
Common Name (eg, your name or your server's hostname) []:api.netkiller.cn
Email Address []:netkiller@msn.com

注意: Common Name (eg, your name or your server's hostname) []:api.netkiller.cn 要跟你的 nginx server_name api.netkiller.cn 一样。

46.3.7.2. spdy

Nginx 配置 spdy

upstream api.netkiller.cn {
    #server api1.netkiller.cn:7000;
    #server api2.netkiller.cn backup;
}

server {
    listen 443 ssl spdy;
    server_name api.netkiller.cn;

    ssl_certificate /etc/nginx/ssl/api.netkiller.cn.crt;
    ssl_certificate_key /etc/nginx/ssl/api.netkiller.cn.key;
    ssl_session_cache shared:SSL:20m;
    ssl_session_timeout 60m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    charset utf-8;
    access_log  /var/log/nginx/api.netkiller.cn.access.log;
    error_log  /var/log/nginx/api.netkiller.cn.error.log;

    location / {
        proxy_pass http://api.netkiller.cn;
        proxy_http_version 1.1;
        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_ignore_client_abort  on;
    }

    #location / {
    #    proxy_pass      http://127.0.0.1:7000;
    #}

}
			

spdy 是google提出的标准,现在已经归入 http2 标准,Nginx 1.10 之后建议使用 http2 替代 spdy.

46.3.7.3. HTTP2

server {
    listen 443 ssl http2;

    ssl_certificate server.crt;
    ssl_certificate_key server.key;
}
			

46.3.7.4. 用户访问 HTTP时强制跳转到 HTTPS

497 - normal request was sent to HTTPS

#让http请求重定向到https请求   

server {
    listen 80;
	error_page 497  https://$host$uri?$args;
	rewrite ^(.*)$  https://$host$1 permanent;
}
server {
    listen 80
    listen 443 ssl http2;

    ssl_certificate server.crt;
    ssl_certificate_key server.key;

	error_page  497              https://$host$uri?$args;

    if ($scheme = http) {
        return 301 https://$server_name$request_uri;
    }
}
			

46.3.7.5. SSL 双向认证

46.3.7.5.1. 生成证书
46.3.7.5.1.1. CA
touch /etc/pki/CA/index.txt
echo 00 > /etc/pki/CA/serial

制作 CA 私钥
openssl genrsa -out ca.key 2048

制作 CA 根证书(公钥)
openssl req -new -x509 -days 3650 -key ca.key -out ca.crt
46.3.7.5.1.2. 服务器端

服务器端证书

制作服务端私钥
openssl genrsa -out server.pem 2048
openssl rsa -in server.pem -out server.key

生成签发请求
openssl req -new -key server.pem -out server.csr	

用 CA 签发
openssl x509 -req -sha256 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 3650 -out server.crt		
46.3.7.5.1.3. 客户端

生成客户端证书

openssl genrsa -des3 -out client.key 2048
openssl req -new -key client.key -out client.csr  

生成签发请求
openssl req -new -key server.pem -out server.csr	

用 CA 签发
openssl ca -in client.csr -cert ca.crt -keyfile ca.key -out client.crt -days 3650
46.3.7.5.1.4. 浏览器证书

生成浏览器证书

openssl pkcs12 -export -inkey client.key -in client.crt -out client.pfx
					
46.3.7.5.1.5. SOAP 证书
cat client.crt client.key > soap.pem
					
	$header = array(
		'local_cert' => "soap.pem", //client.pem文件路径
		'passphrase' => "passw0rd" //client证书密码
		);
	$client = new SoapClient(FILE_WSDL, $header); 					
46.3.7.5.1.6. 过程演示

例 46.3. Nginx SSL 双向认证,证书生成过程

root@VM_7_221_centos /etc/nginx/ssl % openssl genrsa -out ca.key 2048
Generating RSA private key, 2048 bit long modulus
...................................................+++
......................................+++
e is 65537 (0x10001)

root@VM_7_221_centos /etc/nginx/ssl % openssl req -new -x509 -days 3650 -key ca.key -out ca.crt
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) []:GD
Locality Name (eg, city) [Default City]:Shenzhen
Organization Name (eg, company) [Default Company Ltd]:GW
Organizational Unit Name (eg, section) []:DEV
Common Name (eg, your name or your server's hostname) []:api.netkiller.cn
Email Address []:netkiller@msn.com				
root@VM_7_221_centos /etc/nginx/ssl % openssl genrsa -out server.pem 2048
Generating RSA private key, 2048 bit long modulus
.............+++
........................................................+++
e is 65537 (0x10001)			

root@VM_7_221_centos /etc/nginx/ssl % openssl rsa -in server.pem -out server.key
writing RSA key

root@VM_7_221_centos /etc/nginx/ssl % openssl req -new -key server.pem -out server.csr
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) []:GD
Locality Name (eg, city) [Default City]:Shenzhen
Organization Name (eg, company) [Default Company Ltd]:GW
Organizational Unit Name (eg, section) []:DEV
Common Name (eg, your name or your server's hostname) []:api.netkiller.cn
Email Address []:netkiller@msn.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

root@VM_7_221_centos /etc/nginx/ssl % openssl x509 -req -sha256 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 3650 -out server.crt
Signature ok
subject=/C=CN/ST=GD/L=Shenzhen/O=GW/OU=DEV/CN=api.netkiller.cn/emailAddress=netkiller@msn.com
Getting CA Private Key	
46.3.7.5.2. Nginx 配置
mkdir /etc/nginx/ssl
cp server.crt server.key ca.crt /etc/nginx/ssl
cd /etc/nginx/ssl  

/etc/nginx/conf.d/api.netkiller.cn.conf

server {
    listen       443 ssl;
    server_name  api.netkiller.cn;

    access_log off;

    ssl on;
    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;
    ssl_client_certificate /etc/nginx/ssl/ca.crt;
    ssl_verify_client on;

    location / {
        proxy_pass http://localhost:8443;
    }
}				

重启 nginx 服务器

root@VM_7_221_centos /etc/nginx % systemctl restart nginx
				
46.3.7.5.3. 测试双向认证

首先直接请求

root@VM_7_221_centos /etc/nginx % curl -k https://api.netkiller.cn/
<html>
<head><title>400 No required SSL certificate was sent</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<center>No required SSL certificate was sent</center>
<hr><center>nginx</center>
</body>
</html>

使用证书请求

curl --insecure --key client.key --cert ./client.crt:123456  https://api.netkiller.cn

注意: --cert 参数需要写入路径和密码

46.3.8. rewrite

Rewrite Flags
last - 基本上都用这个Flag。
break - 中止Rewirte,不在继续匹配
redirect - 返回临时重定向的HTTP状态302
permanent - 返回永久重定向的HTTP状态301

文件及目录匹配,其中:
-f和!-f用来判断是否存在文件
-d和!-d用来判断是否存在目录
-e和!-e用来判断是否存在文件或目录
-x和!-x用来判断文件是否可执行

正则表达式全部符号解释
~ 为区分大小写匹配
~* 为不区分大小写匹配
!~和!~* 分别为区分大小写不匹配及不区分大小写不匹配
(pattern) 匹配 pattern 并获取这一匹配。所获取的匹配可以从产生的 Matches 集合得到,在VBScript 中使用 SubMatches 集合,在JScript 中则使用 $0…$9 属性。要匹配圆括号字符,请使用 ‘\(’ 或 ‘\)’。
^ 匹配输入字符串的开始位置。
$ 匹配输入字符串的结束位置。
		
server {
	listen 80;
	server_name www.example.com example.com ;
	if ($host = "example.com" )
	{
		rewrite ^/(.*)$ http://www.example.com/$1 permanent;
	}
	if ($host != "www.example.com" )
	{
		rewrite ^/(.*)$ http://www.example.com/$1 permanent;
	}
}
		
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
	if (!-f $request_filename){
	        rewrite /(.*) http://images.example.com/$1;
	}
}
		
if ($host ~ '(.*)\.static\.example\.com' ) {
    set $subdomain $1;
    rewrite  "^/(.*)$"  /$subdomain/$1;
}
		

46.3.8.1. http get 参数处理

需求如下

原理地址:
http://www.netkiller.cn/redirect/index.html?skuid=133

目的地址:
http://www.netkiller.cn/to/133.html

注意:nginx rewrite 并不支持http get 参数处理,也就是说“?”之后的内容rewrite根部获取不到。

下面的例子是行不通的

rewrite ^/redirect/index\.html\?skuid=(\d+)$ /to/$1.html permanent ;

我们需要通过正在查出参数,然后赋值一个变量,再将变量传递给rewrite。具体做法是:

server {
    listen       80;
    server_name www.netkiller.cn;

    #charset koi8-r;
    access_log  /var/log/nginx/test.access.log  main;

    location / {
        root   /www/test;
        index  index.html;

		if ($request_uri ~* "^/redirect/index\.html\?skuid=([0-9]+)$") {
                set $argv1 $1;
                rewrite .* /to/$argv1.html? permanent;
        }
    }
}

测试结果

[neo@netkiller conf.d]$ curl -I http://www.netkiller.cn/redirect/index.html?skuid=133
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Tue, 12 Apr 2016 06:59:33 GMT
Content-Type: text/html
Content-Length: 178
Location: http://www.netkiller.cn/to/133.html
Connection: keep-alive

46.3.8.2. 正则取非

需求如下,除了2015年保留,其他所有页面重定向到新页面

rewrite ^/promotion/(?!2015\/)(.*) https://www.netkiller.cn/promotion.html permanent;
			

46.3.9. upstream 负载均衡

http {
    upstream myapp1 {
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://myapp1;
        }
    }
}
		

46.3.9.1. weight 权重配置

    upstream myapp1 {
        server srv1.example.com weight=3;
        server srv2.example.com;
        server srv3.example.com;
    }
			

46.3.9.2. backup 实现热备

upstream backend {
    server backend1.example.com       weight=5;
    server backend2.example.com:8080;
    server unix:/tmp/backend3;

    server backup1.example.com:8080   backup;
    server backup2.example.com:8080   backup;
}

server {
    location / {
        proxy_pass http://backend;
    }
}
			

46.3.10. fastcgi

46.3.10.1. spawn-fcgi

config php fastcgi

sudo vim /etc/nginx/sites-available/default

        location ~ \.php$ {
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
                include fastcgi_params;
        }

Spawn-fcgi

We still need a script to start our fast cgi processes. We will extract one from Lighttpd. and then disable start script of lighttpd

$ sudo apt-get install lighttpd
$ sudo chmod -x /etc/init.d/lighttpd
		
$ sudo touch /usr/bin/php-fastcgi
$ sudo vim /usr/bin/php-fastcgi

#!/bin/sh
/usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -u www-data -f /usr/bin/php5-cgi
		

fastcgi daemon

$ sudo touch /etc/init.d/nginx-fastcgi
$ sudo chmod +x /usr/bin/php-fastcgi
$ sudo vim /etc/init.d/nginx-fastcgi

This is also a new empty file, add the following and save:

#!/bin/bash
PHP_SCRIPT=/usr/bin/php-fastcgi
RETVAL=0
case "$1" in
start)
$PHP_SCRIPT
RETVAL=$?
;;
stop)
killall -9 php
RETVAL=$?
;;
restart)
killall -9 php
$PHP_SCRIPT
RETVAL=$?
;;
*)
echo "Usage: nginx-fastcgi {start|stop|restart}"
exit 1
;;
esac
exit $RETVAL

We need to change some permissions to make this all work.
$ sudo chmod +x /etc/init.d/nginx-fastcgi

create a test file

sudo vim /var/www/nginx-default/index.php
<?php echo phpinfo(); ?>

46.3.10.2. php-fpm

46.3.10.2.1. php5-fpm
sudo apt-get install php5-cli php5-cgi php5-fpm
			
/etc/init.d/php5-fpm start
			
46.3.10.2.2. 编译 php-fpm
./configure --prefix=/srv/php-5.3.8 \
--with-config-file-path=/srv/php-5.3.8/etc \
--with-config-file-scan-dir=/srv/php-5.3.8/etc/conf.d \
--enable-fpm \
--with-fpm-user=www \
--with-fpm-group=www \
--with-pear \
--with-curl \
--with-gd \
--with-jpeg-dir \
--with-png-dir \
--with-freetype-dir \
--with-xpm-dir \
--with-iconv \
--with-mcrypt \
--with-mhash \
--with-zlib \
--with-xmlrpc \
--with-xsl \
--with-openssl \
--with-mysql=/srv/mysql-5.5.16-linux2.6-i686 \
--with-mysqli=/srv/mysql-5.5.16-linux2.6-i686/bin/mysql_config \
--with-pdo-mysql=/srv/mysql-5.5.16-linux2.6-i686 \
--with-sqlite=shared \
--with-pdo-sqlite=shared \
--disable-debug \
--enable-zip \
--enable-sockets \
--enable-soap \
--enable-mbstring \
--enable-magic-quotes \
--enable-inline-optimization \
--enable-gd-native-ttf \
--enable-xml \
--enable-ftp \
--enable-exif \
--enable-wddx \
--enable-bcmath \
--enable-calendar \
--enable-sqlite-utf8 \
--enable-shmop \
--enable-dba \
--enable-sysvsem \
--enable-sysvshm \
--enable-sysvmsg

make && make install

如果出现 fpm 编译错误,取消--with-mcrypt 可以编译成功。

# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
# chmod 755 /etc/init.d/php-fpm
# ln -s /srv/php-5.3.5 /srv/php
# cp /srv/php/etc/php-fpm.conf.default /srv/php/etc/php-fpm.conf
# cp php.ini-production /srv/php/etc/php.ini
			
groupadd -g 80 www
adduser -o --home /www --uid 80 --gid 80 -c "Web User" www
			

php-fpm.conf

# grep -v ';' /srv/php-5.3.5/etc/php-fpm.conf | grep -v "^$"
[global]
pid = run/php-fpm.pid
error_log = log/php-fpm.log
[www]
listen = 127.0.0.1:9000

user = www
group = www
pm = dynamic
pm.max_children = 2048
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35

pm.max_requests = 500
			
chkconfig --add php-fpm
			
46.3.10.2.2.1. php-fpm 状态
    location /nginx_status {
        stub_status on;
        access_log   off;
        allow 202.82.21.12;
        deny all;
    }
    location ~ ^/(status|ping)$ {
        access_log off;
        allow 202.82.21.12;
        deny all;
        fastcgi_pass 127.0.0.1:9000;
		fastcgi_param SCRIPT_FILENAME $fastcgi_script_name;
        include fastcgi_params;
    }
				
46.3.10.2.3. fastcgi_pass
   location ~ ^(.+\.php)(.*)$
   {
	fastcgi_pass 127.0.0.1:9000;
	fastcgi_index   index.php;
	fastcgi_split_path_info ^(.+\.php)(.*)$;
	fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
	fastcgi_param   PATH_INFO       $fastcgi_path_info;
	fastcgi_param   PATH_TRANSLATED $document_root$fastcgi_path_info;
	include fastcgi_params;
    }
			

Unix Socket

location ~ .*\.(php|php5)?$  {
	#fastcgi_pass  127.0.0.1:9000;
	fastcgi_pass   unix:/dev/shm/php-fpm.sock;
	fastcgi_index index.php;
	include fastcgi.conf;
}
			

46.3.11. return

301 跳转

server {
    listen       80;
    server_name  m.example.com;

    location / {
        return 301 $scheme://www.example.com$request_uri;
    }
}

server {
    listen 80;
    listen 443 ssl;
    server_name www.old-name.com;
    return 301 $scheme://www.new-name.com$request_uri;
}
		

46.3.12. Nginx 变量

可用的全局变量

$args
$content_length
$content_type
$document_root
$document_uri
$host
$http_user_agent
$http_cookie
$http_referer
$limit_rate
$request_body_file
$request_method
$remote_addr
$remote_port
$remote_user
$request_filename
$request_uri
$query_string
$scheme
$server_protocol
$server_addr
$server_name
$server_port
$uri
	

46.3.12.1. $host

抽取域名中的域,例如www.netkiller.cn 返回netkiller.cn

if ($host ~* ^www\.(.*)) {
    set $domain $1;
    rewrite ^(.*) http://user.$domain permanent;
}
		

提取主机

if ($host ~* ^(.+)\.example\.com$) {
    set $subdomain $1;
    rewrite ^(.*) http://www.example.com/$subdomain permanent;
}
		

提取 domain 例如 www.netkiller.cn 提取后 netkiller.cn

只处理二级域名 example.com 不处理三级域名

	if ($host ~* ^([^\.]+)\.([^\.]+)$) {
	   set $domain $1.$2;
	}
		

处理三级域名

	set $domain $host;
	if ($host ~* ^([^\.]+)\.([^\.]+)\.([^\.]+)$) {
	    set $domain $2.$3;
	}

46.3.12.2. http_user_agent

## Block http user agent - wget ##
if ($http_user_agent ~* (Wget|Curl) ) {
   return 403;
}

## Block Software download user agents ##
if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
       return 403;
}

if ($http_user_agent ~ (msnbot|scrapbot) ) {
    return 403;
}

if ($http_user_agent ~ (Spider|Robot) ) {
    return 403;
}

if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /msie/$1 break;
}
		
46.3.12.2.1. 禁止非浏览器访问

禁止非浏览器访问

if ($http_user_agent ~ ^$) {
	return 412;
}
			

测试是否生效

tail -f /var/log/nginx/www.mydomain.com.access.log
			
telnet 192.168.2.10 80
GET /index.html HTTP/1.0
Host: www.mydomain.com
			
46.3.12.2.2. http_user_agent 没有设置不允许访问
	if ($http_user_agent = "") { return 403; }
			

验证测试,首先使用curl -A 指定一个 空的User Agent,应该返回 403.

curl -A ""  http://www.example.com/xml/data.json

<html>
<head><title>403 Forbidden</title></head>
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>

46.3.12.3. http_referer

if ($http_referer ~* "PHP/5.2.14"){return 403;}
		
46.3.12.3.1. valid_referers/invalid_referer
valid_referers none blocked *.example.com example.com;
if ($invalid_referer) {
	#rewrite ^(.*)$  http://www.example.com/cn/$1;
	return 403;
}
			

46.3.12.4. request_filename

    location / {
        root   /www/mydomain.com/info.mydomain.com;
        index  index.html;

		rewrite ^/$  http://www.mydomain.com/;

		valid_referers none blocked *.mydomain.com;
		if ($invalid_referer) {
			return 403;
		}

        proxy_intercept_errors  on;
	    proxy_set_header  X-Real-IP  $remote_addr;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header  Host            $host;

        if (!-f $request_filename) {
          proxy_pass http://old.mydomain.com;
          break;
        }
    }
		

46.3.12.5. request_uri

server {
    listen       80;
    server_name  quote.mydomain.com;

    charset utf-8;
    access_log  /var/log/nginx/quote.mydomain.com.access.log  main;

    location / {
        root   /www/mydomain.com/info.mydomain.com;
        index  index.html ;

		rewrite ^/$  http://www.mydomain.com/;

		valid_referers none blocked *.mydomain.com;
		if ($invalid_referer) {
			#rewrite ^(.*)$  http://www.mydomain.com/cn/$1;
			return 403;
		}

        proxy_intercept_errors  on;
	    proxy_set_header  X-Real-IP  $remote_addr;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header  Host            $host;

		if ( $request_uri ~ "^/xml/(sge|cgse|futures|stock|bonds)\.xml$") {
              proxy_pass http://21.16.22.12/$request_uri;
		break;
        }

        if (!-f $request_filename) {
	          proxy_pass http://cms.mydomain.com;
	          break;
        }

    }

    location ~ \.xml$ {
        proxy_pass http://21.16.22.12/public/datas$request_uri;
        break;
    }

    location ~* ^/public/datas/\w+\.xml$ {
        proxy_pass http://21.16.22.12/$request_uri;
        break;
    }
}
		
#add for yiiframework
        if (!-e $request_filename){
                   rewrite (.*) /index.php break;
        }

        location ~ .*\.php?$
        {
                  #fastcgi_pass  unix:/tmp/php-cgi.sock;
                  include fcgi.conf;
                  fastcgi_pass  127.0.0.1:10080;
                  fastcgi_index index.php;

                  set $path_info $request_uri;

                  if ($request_uri ~ "^(.*)(\?.*)$") {
                        set $path_info $1;
                  }
                  fastcgi_param PATH_INFO $path_info;
        }
#end for yiiframework
		

46.3.12.6. remote_addr

location /name/(match) {
    if ($remote_addr !~ ^10.10.20) {
        limit_rate 10k;
    }

    proxy_buffering off;
    proxy_pass http://10.10.20.1/${1}.html;
}

if ($remote_addr ~* "192.168.0.50|192.168.0.51|192.168.0.56") {
	proxy_pass http://www.netkiller.cn/error;
}
		
location ~ /(\d+) {
    if ($remote_addr ~ (\d+)\.\d+\.) {

    }

    echo $1;
}
		
$ curl 127.0.0.1/134
127

$ curl 192.168.0.1/134
192
		

46.3.12.7. http_cookie

if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
    set $id $1;
}
		

46.3.12.8. request_method

location ~* /restful {
	if ($request_method = PUT ) {
	return 403;
	}
	if ($request_method = DELETE ) {
	return 403;
	}
	if ($request_method = POST ) {
	return 403;
	}
	proxy_method GET;
	proxy_pass http://backend;
}
		
if ($request_method = POST) {
    return 405;
}
		
if ($request_method !~ ^(GET|HEAD|POST)$) {
	return 403;
}
		

46.3.12.9. limit_except

limit_except GET {
	allow 192.168.1.1;
	deny all;
}
		

46.3.12.10. invalid_referer

if ($invalid_referer) {
    return 403;
}
		

46.3.12.11. $request_body - HTTP POST 数据

46.3.12.11.1. 用户日志

将 POST 数据记录到日志中

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" - "$request_body"';
			

注意:用户登录通常使用POST方式,所以记录POST数据到日志会带来安全问题,例如用户密码泄露。

46.3.12.11.2. $request_body 用于缓存

因为nginx 使用 url 作为缓存的key ( Nginx 将url地址 md5后作为缓存的 key ),所以默认情况下 Nginx 只能处理 HTTP GET 缓存。

对于 HTTP POST 请求,提交数据放在HTTP Head 头部提交到服务器的, 提交前后URL始终不变,Nginx 无法区分相同网址两次请求的内容有变化。

但是我们可以自定义 缓存 key 例如: "$request_uri|$request_body" 我们将请求地址加上post内容作为缓存的key,这样nginx 便可以区分每次提交后的页面变化。

 proxy_cache_path /tmp/cache levels=1:2 keys_zone=netkiller:128m inactive=1m;

 server {
  listen 8080;
  server_name localhost;

  location / {
   try_files $uri @backend;
  }

  location @backend {
   proxy_pass http://node1.netkiller.cn:8080;
   proxy_cache netkiller;
   proxy_cache_methods POST;
   proxy_cache_key "$request_uri|$request_body";
   proxy_buffers 8 32k;
   proxy_buffer_size 64k;
   proxy_cache_valid 5s;
   proxy_cache_use_stale updating;
   add_header X-Cached $upstream_cache_status;
  }
 }
			

46.3.12.12. 自定义变量

if ( $host ~* (.*)\.(.*)\.(.*)) {
	set $subdomain $1;
}
location / {
    root  /www/$subdomain;
    index index.html index.php;
}
		
if ( $host ~* (\b(?!www\b)\w+)\.\w+\.\w+ ) {
    set $subdomain /$1;
}

location / {
    root /www/public_html$subdomain;
    index index.html index.php;
}
		

46.3.12.13. if 条件判断

判断相等

if ($query_string = "") {
   	set $args "";
}
		

正则匹配

if ( $host ~* (.*)\.(.*)\.(.*)) {
	set $subdomain $1;
}
location / {
    root /var/www/$subdomain;
    index index.html index.php;
}
		
if ($remote_addr ~ "^(172.16|192.168)" && $http_user_agent ~* "spider") {
    return 403;
}

set $flag 0;
if ($remote_addr ~ "^(172.16|192.168)") {
    set $flag "1";
}
if ($http_user_agent ~* "spider") {
    set $flag "1";
}
if ($flag = "1") {
    return 403;
}
if ($request_method = POST ) {
	return 405;
}
if ($args ~ post=140){
	rewrite ^ http://example.com/ permanent;
}		
location /only-one-if {
    set $true 1;

    if ($true) {
        add_header X-First 1;
    }

    if ($true) {
        add_header X-Second 2;
    }

    return 204;
}		


原文出处:Netkiller 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

时间: 2024-09-28 14:35:25

46.3. nginx 配置文件的相关文章

第 46 章 Nginx

46.1. Installing 46.1.1. Netkiller OSCM 一键安装 (CentOS 7) # curl -s https://raw.githubusercontent.com/oscm/shell/master/web/nginx/stable/nginx.sh | bash 46.1.2. Installing by apt-get under the debain/ubuntu $ sudo apt-get install nginx sudo /etc/init.d

浅析Nginx配置文件中的变量的编写使用_nginx

nginx 的配置文件使用的就是一门微型的编程语言,许多真实世界里的 Nginx 配置文件其实就是一个一个的小程序.当然,是不是"图灵完全的"暂且不论,至少据我观察,它在设计上受 Perl 和 Bourne shell 这两种语言的影响很大.在这一点上,相比 Apache 和 Lighttpd 等其他 Web 服务器的配置记法,不能不说算是 Nginx 的一大特色了.既然是编程语言,一般也就少不了"变量"这种东西(当然,Haskell 这样奇怪的函数式语言除外了).

nginx配置文件nginx.conf中文注释说明_nginx

查了下网络资料,对Nginx配置文件nginx.conf的理解整理如下: 复制代码 代码如下: #定义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.pi

Nginx配置文件(nginx.conf)配置详解(总结)_nginx

现在经常碰到有新用户问一些很基本的问题,最近整理了一下,Nginx的配置文件nginx.conf配置详解如下: user nginx nginx ; Nginx用户及组:用户 组.window下不指定 worker_processes 8; 工作进程:数目.根据硬件调整,通常等于CPU数量或者2倍于CPU. error_log logs/error.log; error_log logs/error.log notice; error_log logs/error.log info; 错误日志:

Nginx配置文件详细说明

在此记录下Nginx服务器nginx.conf的配置文件说明, 部分注释收集与网络. #运行用户 user www-data;     #启动进程,通常设置成和cpu的数量相等 worker_processes  1; #全局错误日志及PID文件 error_log  /var/log/nginx/error.log; pid        /var/run/nginx.pid; #工作模式及连接数上限 events {     use   epoll;             #epoll是多

Nginx 配置文件解析

cycle = ngx_init_cycle(&init_cycle): 1.在内存池中分配一个ngx_cycle_t变量,并初始化它的各个成员. 2.调用core类型的create_conf,实际只有一个ngx_core_module_create_conf函数----初始化ngx_core_conf_t结构(存放core_module支持的指令),保存在ngx_cycle->conf_ctx数组中.可以说,此时,ngx_cycle->conf_ctx数组中只有一个ngx_core_

比较完整的Nginx配置文件nginx.conf常用参数中文详解_nginx

概述 Nginx使用有两三年了,现在经常碰到有新用户问一些很基本的问题,我也没时间一一回答,今天下午花了点时间,结合自己的使用经验,把Nginx的主要配置参数说明分享一下,也参考了一些网络的内容,这篇是目前最完整的Nginx配置参数中文说明了.更详细的模块参数请参考:http://wiki.nginx.org/Main 配置总结 #定义Nginx运行的用户和用户组 user www www; #nginx进程数,建议设置为等于CPU总核心数. worker_processes 8; #全局错误日

nginx配置文件详解中文版_nginx

本文列出了nginx默认配置文件 nginx.conf手大部分命令,并加以中文注释说明,实际配置中可能没有这么复杂,这里只能作为一个参考阅读文档!一.nginx基本配置 复制代码 代码如下: #定义Nginx运行的用户和用户组,系统中必须有此用户,可以是nologinuser www www;   #启动进程,通常设置成和cpu的数量相等worker_processes  1; #全局错误日志及PID文件error_log  /var/log/nginx/error.log; #错误日志定义等级

46.2. Nginx 命令

root@netkiller ~ % nginx -h nginx version: nginx/1.12.1 Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives] Options: -?,-h : this help -v : show version and exit -V : show version and configure options then exit -t : test co