Home | 简体中文 | 繁体中文 | 杂文 | 打赏(Donations) | 云栖社区 | OSChina 博客 | Facebook | Linkedin | 知乎专栏 | Github | Search | About

1.3. nginx.conf 配置文件

1.3.1. 处理器配置

worker_processes = CPU 数量

		
user www;
worker_processes 1;

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

1.3.2. events 配置

连接数配置

		
events {
    worker_connections  4096;
}		
		
		

1.3.3. http 配置

1.3.3.1. 缓冲区相关设置

自定义缓冲区相关设置

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

上传文件提示 client intended to send too large body,配置下面参数可以解决。

			
server {
  ...
  client_max_body_size 200M;
}
			
			

1.3.3.2. 超时设置

超时相关设置

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

1.3.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
			
			
1.3.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;
				
				

1.3.3.4. server_tokens

隐藏nginx版本号

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

1.3.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参数的长度。

1.3.4. 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
	

1.3.4.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;
	}
		
		

1.3.4.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;
}
		
1.3.4.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
			
1.3.4.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>
			
			

1.3.4.3. http_referer

if ($http_referer ~* "PHP/5.2.14"){return 403;}
		
1.3.4.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;
}
			

1.3.4.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;
        }
    }
		

1.3.4.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
		

1.3.4.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
		

1.3.4.7. http_cookie

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

1.3.4.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;
}
		

1.3.4.9. limit_except

limit_except GET {
	allow 192.168.1.1;
	deny all;
}
		

1.3.4.10. invalid_referer

if ($invalid_referer) {
    return 403;
}
		

1.3.4.11. $request_body - HTTP POST 数据

1.3.4.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数据到日志会带来安全问题,例如用户密码泄露。

1.3.4.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;
  }
 }
			

1.3.4.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;
}
		

1.3.4.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;
}		
		
		
		
		
		
		
		
		

1.3.5. server

1.3.5.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;
		...
	}
			
			

1.3.5.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\.)?(.+)$;
			
			

1.3.5.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
			
			

1.3.5.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$;
    ...
}			
			
			

1.3.5.5. location

				location / {
				root /www;
				index index.html index.htm;
				}
			
1.3.5.5.1. 禁止访问特定目录

location 匹配到特定的 path 将拒绝用户访问。

				
    location ~ /\.ht {
        deny  all;
    }
    
	location ~ ^/(config|include)/ {
		deny all;
		break;
	}
				
				
1.3.5.5.2. 引用document_root之外的资源

引用document_root之外的资源需要 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;
	}
				
				
1.3.5.5.3. 处理扩展名
				
    location ~ \.php$ {
        root           /opt/netkiller.cn/cms.netkiller.cn;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /opt/netkiller.cn/cms.netkiller.cn$fastcgi_script_name;
        include        fastcgi_params;
    }				
				
				
1.3.5.5.4. location 中关闭日志
			
        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }
 
        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }			
			
				
				
				

1.3.5.6. 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;
				}
				}
			

1.3.5.7. expires

expires 格式

例 1.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;
				}
				}
			

例 1.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;
					}
				

1.3.5.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';
					}
				
1.3.5.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;
					}
				
1.3.5.7.3. $request_filename
					if (-f $request_filename) {
					expires 1d;
					}
				

1.3.5.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;
				}
			

1.3.5.9. autoindex

开启目录浏览

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

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

1.3.5.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;
				}
				}
			

1.3.5.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;
				}
			
1.3.5.11.1. Cache
				
add_header     Nginx-Cache     "HIT  from  www.example.com";
or
add_header     Nginx-Cache     "$upstream_cache_status  from  www.example.com";
				
				
1.3.5.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;
					}
					}
				

1.3.5.12. 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;
	}
		
			

1.3.6. 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;
	}		
		
		

1.3.6.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
			
			

1.3.6.2. 正则取非

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

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

1.3.7. HTTP2 配置 SSL证书

1.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 一样。

1.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.

1.3.7.3. HTTP2

				server {
				listen 443 ssl http2;

				ssl_certificate server.crt;
				ssl_certificate_key server.key;
				}
			

1.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;
				}
				}
			

1.3.7.5. SSL 双向认证

1.3.7.5.1. 生成证书
1.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
					
					
1.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		
					
					
1.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
					
					
1.3.7.5.1.4. 浏览器证书

生成浏览器证书

						openssl pkcs12 -export -inkey client.key -in client.crt -out client.pfx
					
1.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); 					
					
					
1.3.7.5.1.6. 过程演示

例 1.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	
						
						

1.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
				
1.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 参数需要写入路径和密码

1.3.8. upstream 负载均衡

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

	server {
		listen 80;
		location / {
			proxy_pass http://myapp1;
		}
	}
}
		
		

1.3.8.1. weight 权重配置

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

1.3.8.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;
		}
	}
			
			

1.3.9. Proxy

ngx_http_proxy_module

# cat /etc/nginx/nginx.conf

#user  nobody;
worker_processes  4;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  40960;
        use epoll;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

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

    #access_log  logs/access.log  main;

    access_log  /dev/null;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

upstream backend{
#        server 172.16.0.6:80;
        server 10.0.0.68:80;
        server 10.0.0.69:80;
}


    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

#        location / {
#            root   html;
#            index  index.html index.htm;
#        }

    access_log  /dev/null;
    error_log   /dev/null;


    location / {
#        proxy_pass $scheme://$host$request_uri;
#        proxy_set_header Host $http_host;

#        proxy_buffers 256 4k;
#        proxy_max_temp_file_size 0;

#        proxy_connect_timeout 30;

#        proxy_cache_valid 200 302 10m;
#        proxy_cache_valid 301 1h;
#        proxy_cache_valid any 1m;



         proxy_pass      http://backend;

         proxy_redirect          off;
         proxy_set_header        Host $host;
#         proxy_set_header        X-Real-IP $remote_addr;
#         proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
         client_max_body_size    10m;
         client_body_buffer_size 128k;
         proxy_connect_timeout   30;
         proxy_send_timeout      30;
         proxy_read_timeout      30;
         proxy_buffer_size       4k;
         proxy_buffers           256 4k;
         proxy_busy_buffers_size 64k;
         proxy_temp_file_write_size 64k;
        tcp_nodelay on;
    }


        #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   html;
        }
    }

}
	

1.3.9.1. proxy_cache

/etc/nginx/conf.d/

proxy_cache_path /www/cache keys_zone=www:128m;
server {
	
	location / {
      proxy_pass http://example.net;
      proxy_cache www;
      proxy_cache_key $uri;
      proxy_cache_valid  200 302  60m;
      proxy_cache_valid  404      1m;
    }
}
		

proxy_cache_valid 配置HTTP状态码与缓存时间

proxy_cache_valid any 1m; 任何内容缓存一分钟

proxy_cache_valid  200 302  60m; 状态200,302页面缓存 60分钟

proxy_cache_valid  404      1m;	 状态404页面缓存1分钟	
		
http {
  proxy_cache_path  /var/www/cache levels=1:2 keys_zone=my-cache:8m max_size=1000m inactive=600m;
  proxy_temp_path /var/www/cache/tmp;


  server {
    location / {
      proxy_pass http://example.net;
      proxy_cache mycache;
      proxy_cache_valid  200 302  60m;
      proxy_cache_valid  404      1m;
    }
  }
}
		
location / {
  proxy_pass http://localhost;
  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_headers Set-Cookie;
  proxy_ignore_headers Cache-Control;
  proxy_cache_bypass        $http_secret_header;
  add_header X-Cache-Status $upstream_cache_status;
}
		
server {
          listen       80;
          server_name  example.org;
          root   /var/www;
          index  index.html index.php;

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

	location / {
		proxy_pass       http://backend;
		proxy_set_header  X-Real-IP  $remote_addr;
		proxy_set_header Host $http_host;
		proxy_cache cache;
		proxy_cache_key $host$request_uri;
		proxy_cache_valid 200 304 12h;
		proxy_cache_valid 302 301 12h;
		proxy_cache_valid any 1m;
		proxy_ignore_headers Cache-Control Expires;
		proxy_pass_header Set-Cookie;
	}

}
		
proxy_cache_valid 200 302 10m;
proxy_cache_valid 301      1h;
proxy_cache_valid any      1m;
		

1.3.9.2. rewrite + proxy_pass

需求如下

		
http://www.example.com/images/logo.jpg	=> http://images.example.com/logo.jpg
		
		

如果直接 proxy_pass http://images.example.com; 的后果是http://images.example.com/images/logo.jpg,我们需要去掉images目录,这里使用rewrite /images/(.+)$ /$1 break;实现

    location ^~ /images/ {
                rewrite /images/(.+)$ /$1 break;
                proxy_pass http://images.example.com;
                break;
    }
		

1.3.9.3. request_filename + proxy_pass

如果文件不存在,那么去指定的节点上寻找

   location / {
        root  /www;
        proxy_intercept_errors  on;
        if (!-f $request_filename) {
          proxy_pass http://172.16.1.1;
          break;
        }
    }
	location / {
        root  /www/images;
        proxy_intercept_errors  on;
        if (!-f $request_filename) {
          proxy_pass http://172.16.1.2;
          break;
        }
    }
		

1.3.9.4. $request_uri 与 proxy_pass 联合使用

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

    #charset koi8-r;
    access_log  /var/log/nginx/info.example.com.access.log  main;

    location / {
        root   /www/example.com/info.example.com;
        index  index.html index.htm;

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

	valid_referers none blocked *.example.com;
	if ($invalid_referer) {
		#rewrite ^(.*)$  http://www.example.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;
#
#            proxy_cache one;
#            proxy_cache_valid  200 302 304 10m;
#            proxy_cache_valid  301 1h;
#            proxy_cache_valid  any 1m;

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

        if (!-f $request_filename) {

          proxy_pass http://infoadmin.example.com;
          #proxy_pass http://backend;
          break;
        }
    }

    location ~ ^/index\.php$ {
	return 403;
    }
    location ~ ^/(config|include|crontab|/systemmanage)/ {
	deny all;
	break;
    }
    #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;
    }

}
		

1.3.9.5. try_files 与 proxy_pass 共用

需求,在web目录下索引静态,如果不存在便进入proxy处理,通常proxy后面是tomcat等应用服务器。

我们可以使用 try_files 与 proxy_pass 实现我们的需求

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

    charset utf-8;
    access_log  /var/log/nginx/m.netkiller.cn.access.log;

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

    location @proxy {
		proxy_pass http://127.0.0.1:8000;
        proxy_set_header    Host    $host;
        proxy_set_header    X-Real-IP   $remote_addr;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    #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;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}

    location ~ ^/WEB-INF/ {
        deny  all;
    }
	
    location ~ \.(html|js|css|jpg|png|gif|swf)$ {
        root /www/example.com/m.example.com;
        expires 1d;
    } 
    location ~ \.(ico|fla|flv|mp3|mp4|wma|wmv|exe)$ {
        root /www/example.com/m.example.com;
        expires 7d;
    }
    location ~ \.flv {
        flv;
    }

    location ~ \.mp4$ {
        mp4;
    }

    location /module {
        root /www/example.com/m.example.com;
    }	

}

		

1.3.9.6. Proxy 与 SSI

背景:nginx + tomcat 模式,nginx 开启 SSI , Tomcat 动态页面中输出 SSI 标签

		
# cat  /etc/nginx/conf.d/www.netkiller.cn.conf
server {
    listen       80;
    server_name  www.netkiller.cn;

    charset utf-8;
    access_log  /var/log/nginx/www.netkiller.cn.access.log;

    location / {
        #index  index.html index.htm;
		proxy_pass http://127.0.0.1:8080;
        proxy_set_header    Host    $host;
        proxy_set_header    X-Real-IP   $remote_addr;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    #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;
    }
}		
		
		

test.jsp 文件

		
<%@ page language="java" import="java.util.*,java.text.SimpleDateFormat" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
	<head>
	<title>show time</title>
</head>
<body>
<%

	Date date=new Date();
    SimpleDateFormat ss=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String lgtime=ss.format(date);
%>
	<center>
	<h1><%=lgtime%></h1>
	</center>

	<!--# set var="test" value="Hello netkiller!" -->
	<!--# echo var="test" -->

</body>	
</html>
		
		

测试并查看源码,你会看到SSI标签

		
	<!--# set var="test" value="Hello netkiller!" -->
	<!--# echo var="test" -->		
		
		

解决方案

		
    location / {
        ssi on;
        proxy_set_header Accept-Encoding "";
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header    Host    $host;
        proxy_set_header    X-Real-IP   $remote_addr;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }
		
		

再次测试,你将看不到SSI标签,只能看到文本输出Hello netkiller!

1.3.9.7. Host

Proxy 通过IP地址访问目的主机,如果目的主机是虚拟主机,你就需要告诉目的主机是那个域名。

proxy_set_header Host www.example.com;

proxy_set_header Host $server_name;

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

    charset utf-8;
    access_log  /var/log/nginx/www.example.com.access.log  main;
    
    proxy_set_header   Host $server_name;
    
    location / {
        proxy_pass http://154.21.16.57;
    }

    #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;
    }
}
		

1.3.9.8. expires

location / {
    root /var/www;
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect false;

    if ($request_uri ~* "\.(ico|css|js|gif|jpe?g|png)\?[0-9]+$") {
        expires max;
        break;
    }
    if (-f $request_filename) {
        break;
    }
    if (-f $request_filename/index.html) {
        rewrite (.*) $1/index.html break;
    }
    if (-f $request_filename.html) {
        rewrite (.*) $1.html break;
    }

    proxy_pass http://backend;
}
		

1.3.9.9. X-Forwarded-For

proxy_set_header    X-Real-IP   $remote_addr;
proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
		

1.3.9.10. X-Sendfile

http://wiki.nginx.org/NginxXSendfile

1.3.9.11. proxy_http_version

proxy_http_version 1.0 | 1.1;

1.3.9.12. proxy_set_header

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_set_header User-Agent "Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0";
proxy_set_header X-Forwarded-URI $request_uri;
		

1.3.9.13. proxy_pass_request_headers 透传 Header

有时用户会设置自定义的 HTTP 头信息,这些不符合 HTTP 的头信息如果需要会被 proxy_pass 过滤并丢弃。

		
proxy_pass_request_headers off;
		
		

默认系统是开启的

		
proxy_pass_request_headers on;		
		
		

1.3.9.14. timeout 超时时间

proxy_connect_timeout: 链接超时设置,后端服务器连接的超时时间,发起握手等候响应超时时间。

proxy_read_timeout: 连接成功后,等候后端服务器响应时间,其实已经进入后端的排队之中等候处理,也可以说是后端服务器处理请求的时间。

proxy_send_timeout: 后端服务器数据回传时间,就是在规定时间之内后端服务器必须传完所有的数据。

    location / {
        proxy_pass http://127.0.0.1:8000;
        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_connect_timeout 60s;
        proxy_read_timeout 300s;
        proxy_send_timeout 300s;
    }

		

1.3.9.15. example

/api/ 走代理,其他页面走 Nginx

1.3.9.15.1. 代理特定目录
			
server {
    listen 443 ssl http2;
    server_name  www.netkiller.cn netkiller.cn;

    ssl_certificate ssl/netkiller.cn.crt;
    ssl_certificate_key ssl/netkiller.cn.key;
    ssl_session_cache shared:SSL:20m;
    ssl_session_timeout 60m;

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

    location / {
        root   /opt/netkiller.cn/www.netkiller.cn;
        index  index.html;
    }

    location ^~ /api/ {	
	proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
		proxy_set_header    Host    $host;
		break;
    }

    #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;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny  all;
    }

}
			
			
1.3.9.15.2. upstream 实例
127.0.0.1 		api.example.com
172.16.0.10 	api1.example.com
172.16.0.11 	api2.example.com
			
upstream api.example.com {
    least_conn;
    server api1.example.com;
    server api2.example.com;
}

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

    charset utf-8;
    access_log  /var/log/nginx/api.example.com.access.log;

    location / {
		proxy_pass        http://api.example.com;
		proxy_set_header X-Real-IP  $remote_addr;
		#proxy_set_header Host $host;
		proxy_set_header Host api.example.com;
    }

    #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;
    #}
}
			
1.3.9.15.3. Tomcat 实例
server {
    listen       80;
    server_name  m.netkiller.cn;

    charset utf-8;
    access_log  /var/log/nginx/m.netkiller.cn.access.log;

    location / {
		root /www/example.com/m.example.com;
		rewrite ^(.*)\;jsessionid=(.*)$ $1 break;
		try_files $uri $uri/ @proxy;
    }

    location @proxy {
		proxy_pass http://127.0.0.1:8000;
        proxy_set_header    Host    $host;
        proxy_set_header    X-Real-IP   $remote_addr;
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    #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;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}

    location ~ ^/WEB-INF/ {
        deny  all;
    }
	
    location ~ \.(html|js|css|jpg|png|gif|swf)$ {
        root /www/example.com/m.example.com;
        expires 1d;
    } 
    location ~ \.(ico|fla|flv|mp3|mp4|wma|wmv|exe)$ {
        root /www/example.com/m.example.com;
        expires 7d;
    }
    location ~ \.flv {
        flv;
    }

    location ~ \.mp4$ {
        mp4;
    }

    location /module {
        root /www/example.com/m.example.com;
    }	

}
			

上面的jsessionid处理方式

1.3.9.15.4. Nginx -> Nginx -> Tomcat

背景各种原因需要再Nginx前面再增加一层Nginx虽然需求很变态,本着学习的目的试了试。

这里还使用了 http2 加速 nginx ssl http2 -> nginx ssl http2 -> Tomcat 8080

    server {
        listen       443 ssl http2;
        server_name  www.netkiller.cn;

        ssl_certificate      ssl/netkiller.cn.crt;
        ssl_certificate_key  ssl/netkiller.cn.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

        location / {

	        proxy_buffers 16 4k;
	        proxy_buffer_size 2k;
	
	        proxy_pass https://www.netkiller.cn;
	        proxy_pass_header   Set-Cookie;
	        add_header From     www.netkiller.cn;
	        proxy_set_header    Cookie $http_cookie;
	        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_cookie_domain www.netkiller.cn netkiller.cn;
	        #proxy_cookie_path / "/; secure; HttpOnly";
	        proxy_set_header Accept-Encoding "";
	        proxy_ignore_client_abort  on;

        }
    }
			

有几点需要注意:

如果是443你需要挂在证书,需要透传cookie给目的主机,否则你将无法支持Session,应用程序需要从 X-Forwarded-For 获取IP地址。

1.3.9.15.5. Proxy 处理 Cookie

下面是一个通过 proxy_pass 代理live800的案例,我们需要处理几个地方:

Host头处理,Cookie传递,替换原因页面中的域名,替换文件有html,css,xml,css,js

			
    location ~ ^/k800 {
        #rewrite              ^/live800/(.*)  /$1 break;

        proxy_pass           http://118.23.24.15;
        proxy_pass_header   Set-Cookie;
        proxy_set_header    Accept-Encoding "";
        proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header    Host www.example.com;
        proxy_set_header    Cookie $http_cookie;

        sub_filter_types text/html text/css text/xml text/css text/javascript;
        sub_filter 'www.example.com'  '$host';
        sub_filter_once off;
    }			
			
			
1.3.9.15.6. Proxy 添加 CORS 头
			
server {
    listen       80;
    listen 443 ssl http2;

    server_name api.netkiller.cn;
    ssl_certificate ssl/netkiller.cn.crt;
    ssl_certificate_key ssl/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  main;

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

    location ^~ /api {
		add_header Access-Control-Allow-Origin *;
		add_header Access-Control-Allow-Headers Content-Type,Origin;
		add_header Access-Control-Allow-Methods GET,OPTIONS;
        proxy_pass http://other.example.com/api/;
    }
}
			
			
1.3.9.15.7. 通过 Proxy 汉化 restful 接口

通过 proxy 汉化 restful 接口返回的 json 字符串。

背景,有这样一个需求,前端HTML5通过ajax与restful交互,ajax会显示接口返回json数据,由于js做了混淆无法修改与restful交互的逻辑,但是json反馈结果需要汉化。

汉化前接口如下,返回message为 "message":"Full authentication is required to access this resource"

			
neo@netkiller ~/workspace/Developer/Python % curl http://api.netkiller.cn/restful/member/get/1.json

{"timestamp":1505206067543,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/restful/member/get/1.json"}   
			
			

建立一个代理服务器,代理介于用户和接口之间,ajax 访问接口需要经过这个代理服务器中转。

增加 /etc/nginx/conf.d/api.netkiller.cn.conf 配置文件

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

	charset utf-8;
	
	location / {
		proxy_pass http://localhost:8443;
		proxy_http_version 1.1;
		proxy_set_header    Host    $host;

		sub_filter_types application/json; 
        sub_filter 'Full authentication is required to access this resource'  '用户验证错误';
        sub_filter_once off;
	}

}
			
			

所谓汉化就是字符串替换,使用nginx sub_filter 模块。

重新启动 nginx 然后测试汉化效果

			
neo@netkiller ~/workspace/Developer/Python % curl http://api.netkiller.cn/restful/member/get/1.json

{"timestamp":1505208931927,"status":401,"error":"Unauthorized","message":"用户验证错误","path":"/restful/member/get/1.json"}   
			
			

现在我们看到效果是 "message":"用户验证错误"

1.3.9.15.8. HTTP2 proxy_pass http://
			
server {
    listen       80;
    listen 443 ssl http2;
    server_name  www.netkiller.cn netkiller.cn;

    ssl_certificate ssl/netkiller.cn.crt;
    ssl_certificate_key ssl/netkiller.cn.key;
    ssl_session_cache shared:SSL:20m;
    ssl_session_timeout 60m;

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

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

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

    location ^~ /member/ {
        proxy_pass https://47.75.176.32:443;
		proxy_set_header    Host www.netkiller.cn;
        break;
    }

    location / {
        root   /opt/www.netkiller.cn;
        index  index.html index.php;
    }

    #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  /opt/www.netkiller.cn$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;
    }

}
			
			

1.3.10. fastcgi

1.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(); ?>
		
		

1.3.10.2. php-fpm

1.3.10.2.1. php5-fpm
sudo apt-get install php5-cli php5-cgi php5-fpm
			
/etc/init.d/php5-fpm start
			
1.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
			
1.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;
    }		
				
1.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;
}
			
1.3.10.2.4. nginx example
			
server {
    listen       80;
    listen 443 ssl http2;
    server_name  cms.netkiller.cn;

    ssl_certificate ssl/netkiller.cn.crt;
    ssl_certificate_key ssl/netkiller.cn.key;
    ssl_session_cache shared:SSL:20m;
    ssl_session_timeout 60m;

    charset utf-8;
    access_log  /var/log/nginx/cms.netkiller.cn.access.log  main;

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

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

    location ~ ^/wp-content/uploads/.*\.php$ {
	deny all;
    }

    location / {
        root   /opt/netkiller.cn/cms.netkiller.cn;
        index  index.html index.php;
    }

    #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           /opt/netkiller.cn/cms.netkiller.cn;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /opt/netkiller.cn/cms.netkiller.cn$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;
    #}

}