Home | 简体中文 | 繁体中文 | 杂文 | Search | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 作品与服务 | Email

42.2. nginx 配置文件

worker_processes = CPU 数量

user  www;
worker_processes  1;

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

42.2.1. events

events {
    worker_connections  4096;
}
		

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

42.2.2.1. X-Forwarded-For

real_ip_header X-Forwarded-For;
			

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

gzip_types 压缩类型

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

42.2.2.3. server_tokens

隐藏nginx版本号

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

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

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

42.2.3. server

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

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

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

42.2.3.4. 泛解析主机

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

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

42.2.3.6. expires

expires 格式

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

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

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

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

42.2.3.8. 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. 选项,

42.2.3.9. autoindex

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

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

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

42.2.3.11. stub_status

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

php-fpm 状态

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

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

42.2.3.13. valid_referers

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

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

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

42.2.5. fastcgi

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

42.2.5.2. php-fpm

42.2.5.2.1. php5-fpm
sudo apt-get install php5-cli php5-cgi php5-fpm
			
/etc/init.d/php5-fpm start
			
42.2.5.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
			
42.2.5.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;
    }		
				
42.2.5.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;
}
			

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

}
	

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

}
		

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

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

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

}
		

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

}

		

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

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

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

42.2.6.9. X-Sendfile

http://wiki.nginx.org/NginxXSendfile

42.2.6.10. proxy_http_version

proxy_http_version 1.0 | 1.1;

42.2.6.11. proxy_set_header

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

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

		

42.2.6.13. example

42.2.6.13.1. 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;
    #}
}
			
42.2.6.13.2. 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处理方式

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

42.2.8. ngx_http_flv_module

location ~ \.flv$ {
    flv;
}
		

42.2.9. ngx_http_mp4_module

location /video/ {
    mp4;
    mp4_buffer_size       1m;
    mp4_max_buffer_size   5m;
    mp4_limit_rate        on;
    mp4_limit_rate_after  30s;
}
		

42.2.10. limit_zone

limit_zone   one  $binary_remote_addr  10m;

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

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

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

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

42.2.11.2. http_referer

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

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

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

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

42.2.11.6. 自定义变量

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

42.2.11.7. 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;
}		
		
		
		
		
		
		
		
		
comments powered by Disqus