nginx配置

2018-01-23 10:01 更新

網(wǎng)站上線了,發(fā)現(xiàn)慢點夠可以,特別是圖片及靜態(tài)資源加載,是什么原因?

nodejs的弊端,不太適合處理靜態(tài)資源,配合nginx的反向代理,速度能提升不少。

1、gzip默認沒有開啟

2、node應用的靜態(tài)資源,交給nginx處理,用nginx轉發(fā),實現(xiàn)動靜態(tài)分離

3、開啟靜態(tài)資源緩存

一、nginx配置開啟gzip

  1. gzip_vary on;
  2. gzip_proxied any;
  3. gzip_comp_level 6;
  4. gzip_buffers 16 8k;
  5. gzip_http_version 1.1;
  6. gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;
  7. gzip on;
  8. gzip_disable "msie6";

二、node應用動靜態(tài)資源分離

1、可以考慮用個二級域名,如http://static.jsout.com
2、如果不用二級域名,也可以通過nginx配置目錄達到目的

  1. server {
  2. ...
  3. listen 80;
  4. server_name www.jsout.com jsout.com;
  5. root /var/www/jsout/liblog/www; //指定靜態(tài)資源根目錄
  6. set $node_port 8361;
  7. ...

三、開啟緩存

  1. server {
  2. ...
  3. location ~ /static/ {
  4. etag on;
  5. expires max;
  6. }
  7. ...
  8. }

四、附完整的基于thinkjs的nodejs應用nginx配置(以前端匯http://www.jsout.com為例)

  1. worker_processes 1;
  2. events {
  3. worker_connections 1024;
  4. }
  5. http{
  6. include mime.types;
  7. default_type application/octet-stream;
  8. sendfile on;
  9. tcp_nopush on;
  10. tcp_nodelay on;
  11. keepalive_timeout 60;
  12. client_header_buffer_size 4k;
  13. open_file_cache max=51200 inactive=20s;
  14. open_file_cache_valid 30s;
  15. open_file_cache_min_uses 1;
  16. types_hash_max_size 2048;
  17. client_max_body_size 10m;
  18. gzip_vary on;
  19. gzip_proxied any;
  20. gzip_comp_level 6;
  21. gzip_buffers 16 8k;
  22. gzip_http_version 1.1;
  23. gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;
  24. gzip on;
  25. gzip_disable "msie6";
  26. server {
  27. listen 80;
  28. server_name www.jsout.com jsout.com;
  29. root /var/www/jsout/liblog/www;
  30. set $node_port 8361;
  31. index index.js index.html index.htm;
  32. if ( -f $request_filename/index.html ){
  33. rewrite (.*) $1/index.html break;
  34. }
  35. if ( !-f $request_filename ){
  36. rewrite (.*) /index.js;
  37. }
  38. location = /index.js {
  39. proxy_http_version 1.1;
  40. proxy_set_header Connection "";
  41. proxy_set_header X-Real-IP $remote_addr;
  42. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  43. proxy_set_header Host $http_host;
  44. proxy_set_header X-NginX-Proxy true;
  45. proxy_set_header Upgrade $http_upgrade;
  46. proxy_set_header Connection "upgrade";
  47. proxy_pass http://127.0.0.1:$node_port$request_uri;
  48. proxy_redirect off;
  49. }
  50. location = /production.js {
  51. deny all;
  52. }
  53. location = /testing.js {
  54. deny all;
  55. }
  56. location ~ /static/ {
  57. etag on;
  58. expires max;
  59. }
  60. }
  61. }
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號