知乎專欄 | 多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者” |
worker_processes = CPU 數量
user www; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid;
自定義緩衝區相關設置
client_body_buffer_size 1K; client_header_buffer_size 1k; client_max_body_size 1k; large_client_header_buffers 2 1k;
上傳檔案提示 client intended to send too large body,配置下面參數可以解決。
server { ... client_max_body_size 200M; }
超時相關設置
client_body_timeout 10; client_header_timeout 10; keepalive_timeout 65; send_timeout 10;
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
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參數的長度。
可用的全局變數
$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
抽取域名中的域,例如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; }
## 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; }
禁止非瀏覽器訪問
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
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>
if ($http_referer ~* "PHP/5.2.14"){return 403;}
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; } }
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
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
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; }
將 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數據到日誌會帶來安全問題,例如用戶密碼泄露。
因為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; } }
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; }
判斷相等
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; }
綁定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 images.example.com img1.example.com img2.example.com;
使用通配符匹配
server_name *.example.com server_name www.*;
正則匹配
server_name ~^(.+)\.example\.com$; server_name ~^(www\.)?(.+)$;
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
匹配所有域名
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$; ... }
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; }
為每個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; } }
expires 格式
例 45.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; } }
例 45.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; }
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後,顯示的檔案時間為檔案的伺服器時間
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; } }
# 相關頁面設置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; } }
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; } }
if ($host ~ '(.*)\.example\.com' ) { set $subdomain $1; rewrite "^/(.*)$" /$subdomain/$1; }
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ { if (!-f $request_filename){ rewrite /(.*) http://images.example.com/$1; } }
需求如下
原理地址: 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
需求如下,除了2015年保留,其他所有頁面重定向到新頁面
rewrite ^/promotion/(?!2015\/)(.*) https://www.netkiller.cn/promotion.html permanent;
需求
http://www.example.com/article/10 => http://www.example.com/article/10.html
location / { if (!-e $request_filename){ rewrite ^(.*)$ /$1.html last; break; } }
創建自頒發證書,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 一樣。
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);
例 45.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
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 參數需要寫入路徑和密碼
http { upstream myapp1 { server srv1.example.com; server srv2.example.com; server srv3.example.com; } server { listen 80; location / { proxy_pass http://myapp1; } } }
upstream myapp1 { server srv1.example.com weight=3; server srv2.example.com; server srv3.example.com; }
# 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; } } }
/etc/nginx/conf.d/
proxy_cache_path /www/cache keys_zone=www:128m; server { location / { proxy_pass http://example.net; proxy_cache www; proxy_cache_key $uri; proxy_cache_valid 200 302 60m; proxy_cache_valid 404 1m; } }
proxy_cache_valid 配置HTTP狀態碼與緩存時間
proxy_cache_valid any 1m; 任何內容緩存一分鐘 proxy_cache_valid 200 302 60m; 狀態200,302頁面緩存 60分鐘 proxy_cache_valid 404 1m; 狀態404頁面緩存1分鐘
http { proxy_cache_path /var/www/cache levels=1:2 keys_zone=my-cache:8m max_size=1000m inactive=600m; proxy_temp_path /var/www/cache/tmp; server { location / { proxy_pass http://example.net; proxy_cache mycache; proxy_cache_valid 200 302 60m; proxy_cache_valid 404 1m; } } }
location / { proxy_pass http://localhost; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_ignore_headers Set-Cookie; proxy_ignore_headers Cache-Control; proxy_cache_bypass $http_secret_header; add_header X-Cache-Status $upstream_cache_status; }
server { listen 80; server_name example.org; root /var/www; index index.html index.php; location ~* .+.(ico|jpg|gif|jpeg|css|js|flv|png|swf)$ { expires max; } location / { proxy_pass http://backend; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; proxy_cache cache; proxy_cache_key $host$request_uri; proxy_cache_valid 200 304 12h; proxy_cache_valid 302 301 12h; proxy_cache_valid any 1m; proxy_ignore_headers Cache-Control Expires; proxy_pass_header Set-Cookie; } }
proxy_cache_valid 200 302 10m; proxy_cache_valid 301 1h; proxy_cache_valid any 1m;
需求如下
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; }
如果檔案不存在,那麼去指定的節點上尋找
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; } }
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; } }
需求,在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; } }
背景: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!
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; } }
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; }
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_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header User-Agent "Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0"; proxy_set_header X-Forwarded-URI $request_uri;
有時用戶會設置自定義的 HTTP 頭信息,這些不符合 HTTP 的頭信息如果需要會被 proxy_pass 過濾並丟棄。
proxy_pass_request_headers off;
預設系統是開啟的
proxy_pass_request_headers on;
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; }
/api/ 走代理,其他頁面走 Nginx
server { listen 443 ssl http2; server_name www.netkiller.cn netkiller.cn; ssl_certificate ssl/netkiller.cn.crt; ssl_certificate_key ssl/netkiller.cn.key; ssl_session_cache shared:SSL:20m; ssl_session_timeout 60m; charset utf-8; #access_log /var/log/nginx/host.access.log main; location / { root /opt/netkiller.cn/www.netkiller.cn; index index.html; } location ^~ /api/ { proxy_pass http://127.0.0.1:8080; proxy_http_version 1.1; proxy_set_header Host $host; break; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # location ~ /\.ht { deny all; } }
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; #} }
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處理方式
背景各種原因需要再Nginx前面再增加一層Nginx雖然需求很變態,本着學習的目的試了試。
這裡還使用了 http2 加速 nginx ssl http2 -> nginx ssl http2 -> Tomcat 8080
server { listen 443 ssl http2; server_name www.netkiller.cn; ssl_certificate ssl/netkiller.cn.crt; ssl_certificate_key ssl/netkiller.cn.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5; # ssl_prefer_server_ciphers on; location / { proxy_buffers 16 4k; proxy_buffer_size 2k; proxy_pass https://www.netkiller.cn; proxy_pass_header Set-Cookie; add_header From www.netkiller.cn; proxy_set_header Cookie $http_cookie; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_cookie_domain www.netkiller.cn netkiller.cn; #proxy_cookie_path / "/; secure; HttpOnly"; proxy_set_header Accept-Encoding ""; proxy_ignore_client_abort on; } }
有幾點需要注意:
如果是443你需要掛在證書,需要透傳cookie給目的主機,否則你將無法支持Session,應用程序需要從 X-Forwarded-For 獲取IP地址。
下面是一個通過 proxy_pass 代理live800的案例,我們需要處理幾個地方:
Host頭處理,Cookie傳遞,替換原因頁面中的域名,替換檔案有html,css,xml,css,js
location ~ ^/k800 { #rewrite ^/live800/(.*) /$1 break; proxy_pass http://118.23.24.15; proxy_pass_header Set-Cookie; proxy_set_header Accept-Encoding ""; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host www.example.com; proxy_set_header Cookie $http_cookie; sub_filter_types text/html text/css text/xml text/css text/javascript; sub_filter 'www.example.com' '$host'; sub_filter_once off; }
server { listen 80; listen 443 ssl http2; server_name api.netkiller.cn; ssl_certificate ssl/netkiller.cn.crt; ssl_certificate_key ssl/netkiller.cn.key; ssl_session_cache shared:SSL:20m; ssl_session_timeout 60m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; charset utf-8; access_log /var/log/nginx/api.netkiller.cn.access.log main; location / { proxy_pass http://127.0.0.1:7000; } location ^~ /api { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Headers Content-Type,Origin; add_header Access-Control-Allow-Methods GET,OPTIONS; proxy_pass http://other.example.com/api/; } }
通過 proxy 漢化 restful 介面返回的 json 字元串。
背景,有這樣一個需求,前端HTML5通過ajax與restful交互,ajax會顯示介面返回json數據,由於js做了混淆無法修改與restful交互的邏輯,但是json反饋結果需要漢化。
漢化前介面如下,返回message為 "message":"Full authentication is required to access this resource"
neo@netkiller ~/workspace/Developer/Python % curl http://api.netkiller.cn/restful/member/get/1.json {"timestamp":1505206067543,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/restful/member/get/1.json"}
建立一個代理伺服器,代理介於用戶和介面之間,ajax 訪問介面需要經過這個代理伺服器中轉。
增加 /etc/nginx/conf.d/api.netkiller.cn.conf 配置檔案
server { listen 80; server_name api.netkiller.cn; charset utf-8; location / { proxy_pass http://localhost:8443; proxy_http_version 1.1; proxy_set_header Host $host; sub_filter_types application/json; sub_filter 'Full authentication is required to access this resource' '用戶驗證錯誤'; sub_filter_once off; } }
所謂漢化就是字元串替換,使用nginx sub_filter 模組。
重新啟動 nginx 然後測試漢化效果
neo@netkiller ~/workspace/Developer/Python % curl http://api.netkiller.cn/restful/member/get/1.json {"timestamp":1505208931927,"status":401,"error":"Unauthorized","message":"用戶驗證錯誤","path":"/restful/member/get/1.json"}
現在我們看到效果是 "message":"用戶驗證錯誤"
server { listen 80; listen 443 ssl http2; server_name www.netkiller.cn netkiller.cn; ssl_certificate ssl/netkiller.cn.crt; ssl_certificate_key ssl/netkiller.cn.key; ssl_session_cache shared:SSL:20m; ssl_session_timeout 60m; charset utf-8; #access_log /var/log/nginx/host.access.log main; error_page 497 https://$host$uri?$args; if ($scheme = http) { return 301 https://$server_name$request_uri; } location ^~ /member/ { proxy_pass https://47.75.176.32:443; proxy_set_header Host www.netkiller.cn; break; } location / { root /opt/www.netkiller.cn; index index.html index.php; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { root html; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /opt/www.netkiller.cn$fastcgi_script_name; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # location ~ /\.ht { deny all; } }
mkdir -p /var/cache/nginx/ipfs chown nginx:root /var/cache/nginx/ipfs
proxy_cache_path /var/cache/nginx/ipfs keys_zone=ipfs:4096m; server { listen 80; server_name localhost; #charset koi8-r; access_log /var/log/nginx/ipfs.access.log; location / { proxy_pass http://127.0.0.1:8080; proxy_cache ipfs; proxy_cache_valid 200 30d; expires max; } location ~* .+.(mp4)$ { rewrite ^/(.*)\.mp4$ /$1 last; proxy_pass http://127.0.0.1:8080; proxy_cache ipfs; proxy_cache_valid 200 30d; expires max; mp4; } #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; } }
查看緩存情況
[root@netkiller ~]# find /var/cache/nginx/ipfs/ /var/cache/nginx/ipfs/ /var/cache/nginx/ipfs/47c3015c7a497f26f650a817f5a179ab
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(); ?>
./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
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; }
server { listen 80; listen 443 ssl http2; server_name cms.netkiller.cn; ssl_certificate ssl/netkiller.cn.crt; ssl_certificate_key ssl/netkiller.cn.key; ssl_session_cache shared:SSL:20m; ssl_session_timeout 60m; charset utf-8; access_log /var/log/nginx/cms.netkiller.cn.access.log main; error_page 497 https://$host$uri?$args; if ($scheme = http) { return 301 https://$server_name$request_uri; } location ~ ^/wp-content/uploads/.*\.php$ { deny all; } location / { root /opt/netkiller.cn/cms.netkiller.cn; index index.html index.php; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { root /opt/netkiller.cn/cms.netkiller.cn; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /opt/netkiller.cn/cms.netkiller.cn$fastcgi_script_name; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} }