| 知乎专栏 | 
绑定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;
		...
	}
			
		
	
			
# 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 *.example.com server_name www.*;
正则匹配
server_name ~^(.+)\.example\.com$; server_name ~^(www\.)?(.+)$;
泛解析主机
			
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$;
    ...
}			
			
			
		
		
	location / {
	root /www;
	index index.html index.htm;
	}
			
			
		
		
		
		location 匹配到特定的 path 将拒绝用户访问。
				
    location ~ /\.ht {
        deny  all;
    }
    
	location ~ ^/(config|include)/ {
		deny all;
		break;
	}
				
			
		引用document_root之外的资源需要 root 绝对路径指向目标文件夹
				
	location / {
		root /www/example.com/m.example.com;
		try_files $uri $uri/ @proxy;
	}
	location ^~ /module/ {
		root /www/example.com/www.example.com;
	}
	# 下面的写法是错误的,通过error_log 我们可以看到被定为到/www/example.com/m.example.com/module
	location /module/ {
		root /www/example.com/www.example.com;
	}
				
			
		
				
    location ~ \.php$ {
        root           /opt/netkiller.cn/cms.netkiller.cn;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /opt/netkiller.cn/cms.netkiller.cn$fastcgi_script_name;
        include        fastcgi_params;
    }				
				
			
		
			
        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }
 
        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }			
			
			
		
				
    location ~ /(dev|stage|prod) {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header REMOTE-HOST $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://api.netkiller.cn:8080;
    }				
				
			
			使用正则表达式匹配多个目录
			
# 区分大小写匹配 /dir1/ 或 /dir2/ 或 /dir3/
location ~ ^/(dir1|dir2|dir3)/ {
    # 配置内容
    root /var/www;
    index index.html;
}
# 不区分大小写匹配(加上 ~*)
location ~* ^/(dir1|dir2|dir3)/ {
    # 配置内容
}
			
			
		为每个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;
	}
}
			
		
		案例
				
server {
    listen       80;
    listen       443 ssl http2;
    server_name  report.netkiller.cn;
    include /etc/nginx/default.d/*.conf;
    access_log /var/log/nginx/report.netkiller.cn.access.log;
    error_log /var/log/nginx/report.netkiller.cn.error.log;
    error_page 497 https://$host$uri?$args;
    if ($scheme = http) {
	    return 301 https://$server_name$request_uri;
    }
    location / {
    	root   /opt/netkiller.cn/report.netkiller.cn;
	    index  index.html;
    }
    location /api/ {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header REMOTE-HOST $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://dashboard.netkiller.cn:8080/;
    }
    location /file/download { 
        proxy_set_header Host $host; 
        proxy_set_header X-Real-IP $remote_addr; 
        proxy_set_header REMOTE-HOST $remote_addr; 
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
        proxy_pass http://dashboard.netkiller.cn:8080; 
    }
    error_page 404 /404.html;
        location = /40x.html {
    }
    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
    }
}				
				
		
		⚠️注意,两个 proxy_pass 的区别:
/api/ 匹配后等效 /api/* = http://dashboard.netkiller.cn:8080/*
/file/download 匹配等效 /file/download/* = http://dashboard.netkiller.cn:8080/file/download/*
root 定位目录,例如 http://www.netkiller.cn/static/neo.js
		
    location ^~ /static/ {
        root /usr/share/nginx/dev/;
        autoindex on;
    }
		
		
		定位结果 /usr/share/nginx/dev/static/neo.js
我们不希望出现 static 这层目录,就需要使用 alias 替代 root
		
    location ^~ /static/ {
        alias /usr/share/nginx/dev/;
        autoindex on;
    }
		
		
		最终文件路径是 /usr/share/nginx/dev/neo.js
			
	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;
		}
	}
			
		
	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
创建自颁发证书,SSL有两种证书模式,单向认证和双向认证,下面是单向认证模式。
mkdir -p /etc/pki/nginx/private/ cd /etc/pki/nginx/ openssl req -x509 -nodes -days 365 -newkey rsa:4096 -keyout /etc/pki/nginx/private/server.key -out /etc/pki/nginx/server.crt
建议使用域名命名证书
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 一样。
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.
			
	server {
		listen 443 ssl http2;
	
		ssl_certificate server.crt;
		ssl_certificate_key server.key;
	}
			
			
		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;
		}
	}
			
			
		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
服务器端证书
制作服务端私钥 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
生成客户端证书
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
cat client.crt client.key > soap.pem
$header = array( 'local_cert' => "soap.pem", //client.pem文件路径 'passphrase' => "passw0rd" //client证书密码 ); $client = new SoapClient(FILE_WSDL, $header);
例 2.1. 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
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
首先直接请求
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 参数需要写入路径和密码
expires 格式
例 2.2. 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;
			}
		}
			
		
		例 2.3. 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;
	}
				
			
		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';
	}
				
			
		
				
		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;
	}
				
			
		
			
	#防止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;
	}
			
		
	开启目录浏览
			
# vim /etc/nginx/sites-enabled/default
location / {
	autoindex on;
}
			
		
		# /etc/init.d/nginx reload Reloading nginx configuration: nginx.
另外Nginx的目录流量有两个比较有用的参数,可以根据自己的需求添加:
autoindex_exact_size off; 默认为on,显示出文件的确切大小,单位是bytes。 改为off后,显示出文件的大概大小,单位是kB或者MB或者GB autoindex_localtime on; 默认为off,显示的文件时间为GMT时间。 改为on后,显示的文件时间为文件的服务器时间
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;
	}
		
		
	# 相关页面设置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;
	}
			
			
			add_header Nginx-Cache "HIT from www.example.com"; or add_header Nginx-Cache "$upstream_cache_status from www.example.com";
				
		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;
		}
	}
				
			
			允许 所有头部 所有域 所有方法
				
server {
	...
	location / {
		add_header 'Access-Control-Allow-Origin' '*';
		add_header 'Access-Control-Allow-Headers' '*';
		add_header 'Access-Control-Allow-Methods' '*';
		# OPTIONS 直接返回204
		if ($request_method = 'OPTIONS') {
			return 204;
		}
	}
	...
}				
				
			
			使用 $http_origin 变量
				
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
	add_header 'Access-Control-Max-Age' 1728000;
	add_header 'Content-Type' 'text/plain; charset=utf-8';
	add_header 'Content-Length' 0;
	return 204;
}