1.3.nginx配置檔案

玄學醬發表於2018-01-01

worker_processes = CPU 數量

user  www;
worker_processes  1;

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

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

1.3.2. events

events {
    worker_connections  4096;
}
		

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

隱藏nginx版本號

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

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

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

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

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

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

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

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

1.3.6.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.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`;
}
				
1.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;
}
				
1.3.6.7.3. $request_filename
if (-f $request_filename) {
     expires 1d;         
}				
				

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

1.3.6.9. autoindex

開啟目錄瀏覽

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

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

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

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

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

1.3.8.2. 正則取非

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

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

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

1.3.9.1. weight 權重配置

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

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

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

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

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

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

1.3.12.3. http_referer

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

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

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

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

1.3.12.7. http_cookie

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

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

1.3.12.9. limit_except

limit_except GET {
	allow 192.168.1.1;
	deny all;
}
		

1.3.12.10. invalid_referer

if ($invalid_referer) {
    return 403;
}
		

1.3.12.11. $request_body – HTTP POST 資料

1.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資料到日誌會帶來安全問題,例如使用者密碼洩露。

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

1.3.12.12. 自定義變數

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

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

1.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 系列 手札
本文作者:陳景峰
轉載請與作者聯絡,同時請務必標明文章原始出處和作者資訊及本宣告。