Home | Mirror | SearchITEYE 博客 | OSChina 博客 | 51CTO 博客

3.3. nginx 配置檔案

worker_processes = CPU 數量

user  www;
worker_processes  1;

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

3.3.1. events

events {
    worker_connections  4096;
}
		

3.3.2. http 配置

3.3.2.1. X-Forwarded-For

real_ip_header X-Forwarded-For;
			

3.3.2.2. gzip

gzip  on;
gzip_min_length  1000;
gzip_buffers     4 8k;
gzip_types       text/plain application/x-javascript text/css text/html 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;
			

3.3.2.3. server_tokens

隱藏nginx版本號

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

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

3.3.3. server

3.3.3.1. 單域名虛擬主機

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

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

3.3.3.3. 泛解析主機

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

3.3.3.4. location

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

3.3.3.5. expires

expires 格式

例 3.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)$
{
        expires      1d;
        access_log off;
}
			
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;
        }
}
			

add_header 實例

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

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

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

3.3.3.7. auth_basic

cd /usr/local/nginx/conf
server {
	listen 80;
	server_name www.example.com;
	root /var/www/htdocs;
	index index.html;

	location / {
		try_files $uri $uri/ /index.html;
		auth_basic            "Login";
        auth_basic_user_file  htpasswd;
	}
}
			

生成密碼檔案

$ sudo apt-get install apache2-utils

htpasswd -c -d htpasswd user_name
			
[提示]提示

必須使用 -d Force CRYPT encryption of the password. 選項,

3.3.3.8. autoindex

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

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

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

3.3.3.10. Cache

			
add_header     Nginx-Cache     "HIT  from  www.example.com";
or
add_header     Nginx-Cache     "$upstream_cache_status  from  www.example.com";
			
			

3.3.3.11. stub_status

location /nginx_status {
	stub_status on;
	access_log  off;
	allow 127.0.0.1;
	deny all;
}
			

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

3.3.3.13. valid_referers

例 3.3. Example: valid_referers

location /photos/ {
  valid_referers none blocked www.mydomain.com mydomain.com;

  if ($invalid_referer) {
    return   403;
  }
}
				
location ~* \.(gif|jpg|jpeg|png|bmp|txt|zip|jar|swf)$ {
	valid_referers none blocked *.mydomain.com;
	if ($invalid_referer) {
		rewrite ^/  http://www.mydomain.com/default.gif;
		#return 403;
	}

}

location /images/ {
	alias /www/images/;
	valid_referers none blocked *.mydomain.com;
	if ($invalid_referer) {
		rewrite ^/  http://www.mydomain.com/default.gif;
	}
}
				

3.3.4. Proxy

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

}
		

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

3.3.4.2. proxy_cache

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

}
			

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

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

}
			

3.3.4.5. X-Sendfile

http://wiki.nginx.org/NginxXSendfile


			

3.3.5. limit_zone

limit_zone   one  $binary_remote_addr  10m;

server {
	location /download/ {
	limit_conn   one  1;
}
		

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

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

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

3.3.6.2. http_referer

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

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

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

3.3.6.5. 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;
}
		
location ~ /(\d+) {
    if ($remote_addr ~ (\d+)\.\d+\.) {

    }

    echo $1;
}
		
$ curl 127.0.0.1/134
127

$ curl 192.168.0.1/134
192
		

3.3.6.6. 自定義變數

if ( $host ~* (.*)\.(.*)\.(.*)) {
	set $subdomain $1;
}
location / {
    root  html/$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;
}
		
comments powered by Disqus