第17章 附录

setting 常用设置

官方地址: https://docs.djangoproject.com/zh-hans/2.0/ref/settings/

DATABASES

默认值: 空字典 {},包含要与django一起使用的所有数据库的设置的字典。是一个嵌套字段,其内容将数据库别名映射到包含单个数据选项的字典。

该DATABAES必须设置default数据库,还可以指定任意数量的其他附加的数据库

  1. # sqlite3
  2. DATABASES = {
  3. 'default': {
  4. 'ENGINE': 'django.db.backends.sqlite3',
  5. 'NAME': 'mydatabase',
  6. }
  7. }
  8. # postgresql
  9. DATABASES = {
  10. 'default': {
  11. 'ENGINE': 'django.db.backends.postgresql',
  12. 'NAME': 'mydatabase',
  13. 'USER': 'mydatabaseuser',
  14. 'PASSWORD': 'mypassword',
  15. 'HOST': '127.0.0.1',
  16. 'PORT': '5432',
  17. }
  18. }

可以使用以下内部选项来进行更复杂的配置:

TIME_ZONE

默认 None,表示存储在此数据库中的日期时间的字符串(假设它不支持时区)或者None。该DATABASES设置的内部选项接受与掌握TIME_ZONE设置相同的值

TEST

默认值: 空字典,测试数据库的设置字典;有关测试数据库的创建和使用的更多详细信息,请参阅测试数据库

APPEND_SLASH

默认 True, 如果请求URL与URLconf中的任何模式都不匹配,并且它不心斜杠结尾,则 django 会向相同的URL发出HTTP重定向,并附加斜杠。请注意,重定向可能导致POST请求中提交的任何数据丢失。

APPEND_SLASH设置项由中间件 CommonMiddleware 提供支持。

nginx设置

官方地址:https://nginx.org/en/docs/dirindex.html

Syntax: uwsgi_pass [protocol://]address;
Default:
Context: location
, if in location

设置uwsgi服务器的协议和地址。地址支持域名或者IP以及端口号,当然也可以使用UNIX套接字路径 uwsgi_pass unix:/tmp/uwsgi.socket;

如果域名解析为多个地址,则所有这些地址将以循环方式使用。此外,可以将地址指定为 服务器组 server group

  1. upstream backend { # backend 上游服务器组名字
  2. server backend1.example.com weight=5;
  3. server backend2.example.com:8080;
  4. server unix:/tmp/backend3;
  5. server backup1.example.com:8080 backup;
  6. server backup2.example.com:8080 backup;
  7. }
  8. server {
  9. location / {
  10. proxy_pass http://backend;
  11. }
  12. }

location语法

  1. location [=|~|~*|^~] pattern {
  2. }
  3. # = 精确匹配
  4. # ^~ 以某个常规字符串开头,不是正则匹配
  5. # ~ 区分大小写的正则匹配
  6. # ~* 不区分大小写的正则匹配
  7. # / 通用匹配,匹配所有

规则解释:

  1. location = 精确匹配 > location 完整路径 > location ^~ 路径 > location ~,~* 正则顺序 > location 部分起始路径 > location /
  2. # location ^~ 路径 # 以某个字符串开头,不是正则匹配
  3. location = / {
  4. proxy_pass http://tomcat:8080/index
  5. }
  6. location ^~ /static/ {
  7. root /webroot/static/;
  8. }
  9. location / {
  10. proxy_pass http://tomcat:8080/;
  11. }

location配置优先级

  • 普通匹配与顺序无关,因为按照匹配的长短来取匹配结果。
  • 正则匹配与顺序有关,因为是从上往下匹配。(首先匹配,取其之。结束解析过程)

nginx conf 配置参考

  1. http重定向到https

  1. # the upstream component nginx needs to connect to
  2. upstream django {
  3. #server unix:///tmp/uwsgi.sock;
  4. #server unix:/tmp/uwsgi.sock;
  5. #server 192.168.0.152:8080; # for a web port socket (we'll use this first)
  6. server 127.0.0.1:8080; # for a web port socket (we'll use this first)
  7. }
  8. # http site conf
  9. server {
  10. listen 80;
  11. server_name 192.168.0.152;
  12. charset utf-8;
  13. # max upload size
  14. client_max_body_size 75M; # adjust to taste
  15. # Django media
  16. location /media {
  17. alias /srv/WEME_BE/weme/media/;
  18. }
  19. location /static {
  20. alias /srv/WEME_BE/weme/static/;
  21. }
  22. location /xadmin {
  23. proxy_pass http://127.0.0.1:8080/xadmin;
  24. }
  25. location /api/v1 {
  26. proxy_pass http://127.0.0.1:8080;
  27. }
  28. location / {
  29. if ($request_method = 'OPTIONS') {
  30. add_header 'Access-Control-Allow-Origin' '*';
  31. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  32. add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
  33. add_header 'Access-Control-Max-Age' 1728000;
  34. add_header 'Content-Type' 'text/plain; charset=utf-8';
  35. add_header 'Content-Length' 0;
  36. return 204;
  37. }
  38. root /srv/weme_http/;
  39. index index.html index.htm;
  40. }
  41. }
  42. # configuration of the server
  43. # https site conf
  44. server {
  45. # the port your site will be served on
  46. listen 443 ssl;
  47. server_name 192.168.0.152; # substitute your machine's IP address or FQDN
  48. charset utf-8;
  49. ssl on;
  50. ssl_certificate /etc/nginx/ssl/192.168.0.152.crt;
  51. ssl_certificate_key /etc/nginx/ssl/192.168.0.152.key;
  52. proxy_request_buffering off;
  53. proxy_buffering off;
  54. proxy_connect_timeout 75s;
  55. proxy_read_timeout 300s;
  56. # max upload size
  57. client_max_body_size 75M; # adjust to taste
  58. # Django media
  59. location /media {
  60. alias /srv/WEME_BE/weme/media/; # your Django project's media files - amend as required
  61. }
  62. location /static {
  63. alias /srv/WEME_BE/weme/static/; # your Django project's static files - amend as required
  64. }
  65. location /xadmin {
  66. proxy_pass http://127.0.0.1:8080/xadmin;
  67. }
  68. location /api/v1 {
  69. proxy_pass http://127.0.0.1:8080;
  70. }
  71. location / {
  72. if ($request_method = 'OPTIONS') {
  73. add_header 'Access-Control-Allow-Origin' '*';
  74. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  75. add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
  76. add_header 'Access-Control-Max-Age' 1728000;
  77. add_header 'Content-Type' 'text/plain; charset=utf-8';
  78. add_header 'Content-Length' 0;
  79. return 204;
  80. }
  81. root /srv/weme/;
  82. index index.html index.htm;
  83. }
  84. }

需要根据站点配置做相应修改

  1. # /etc/nginx/conf.d/mysite_nginx.conf
  2. # the upstream component nginx needs to connect to
  3. upstream django {
  4. # server unix:///path/to/your/mysite/mysite.sock; # for a file socket
  5. server 127.0.0.1:8001; # for a web port socket (we'll use this first)
  6. }
  7. # configuration of the server
  8. server {
  9. # the port your site will be served on
  10. listen 80;
  11. # the domain name it will serve for
  12. server_name .example.com; # substitute your machine's IP address or FQDN
  13. charset utf-8;
  14. # max upload size
  15. client_max_body_size 75M; # adjust to taste
  16. # Django media
  17. location /media {
  18. alias /path/to/your/mysite/media; # your Django project's media files - amend as required
  19. }
  20. location /static {
  21. alias /path/to/your/mysite/static_dist; # your Django project's static files - amend as required
  22. }
  23. # Finally, send all non-media requests to the Django server.
  24. location / {
  25. uwsgi_pass django; # go to [upstream django]
  26. include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed
  27. }
  28. }

项目实例1 - uwsgi

  1. upstream django {
  2. server 127.0.0.1:3031;
  3. }
  4. server {
  5. listen 80;
  6. #server_name .example.com;
  7. server_name 192.168.0.130;
  8. client_max_body_size 75M;
  9. charset utf-8;
  10. #access_log /var/log/nginx/ebee_access.log;
  11. error_log /var/log/nginx/ebee_error.log;
  12. location /media {
  13. alias /var/www/ebee/static/media/;
  14. }
  15. location /static {
  16. alias /var/www/ebee/static/;
  17. }
  18. # Finally, send all non-media requests to the Django server.
  19. location / {
  20. uwsgi_pass django;
  21. #include /var/www/ebee/ebee/uwsgi_params;
  22. include /etc/nginx/uwsgi_params;
  23. }
  24. }

错误信息很好理解,就是说 Access-Control-Allow-Origin 有两个值,但是浏览器只准许有一个值,所以报错。

增强nginx性能方法


优化代码逻辑的极限是移除所有逻辑;


优化请求的极限是不发送任何请求。

这两点通过缓存都可以实现。

项目实例

  1. # vim /etc/nginx/nginx.conf
  2. user www-data;
  3. worker_processes auto;
  4. pid /run/nginx.pid;
  5. events {
  6. worker_connections 768;
  7. # multi_accept on;
  8. }
  9. http {
  10. # Basic Settings
  11. # sendfile 提高 Nginx 静态资源托管效率。sendfile 是一个系统调用,直接在内核空间完成文件发送,不需要先 read 再 write,没有上下文切换开销。
  12. sendfile on;
  13. # socket选项,只有在启用了 sendfile 之后才生效;启用它之后,数据包会累计到一定大小之后才会发送,减小了额外开销,提高网络效率。
  14. tcp_nopush on;
  15. tcp_nodelay on; # socket选项,启用后禁用 Nagle 算法
  16. keepalive_timeout 65;
  17. types_hash_max_size 2048;
  18. server_tokens off;
  19. # server_names_hash_bucket_size 64;
  20. # server_name_in_redirect off;
  21. include /etc/nginx/mime.types;
  22. default_type application/octet-stream;
  23. # SSL Settings
  24. ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
  25. ssl_prefer_server_ciphers on;
  26. ssl_ciphers ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GC$
  27. # gzip settings
  28. gzip on;
  29. # gizp_disable 接受一个正则表达式,当请求头中的UserAgent满足这个正则时,响应不会启用gzip
  30. # 特别地,指令值 msie6 等价于 MSIE [4-6]\.,但性能更好一些。
  31. gzip_disable "msie6";
  32. gzip_vary on; # 输出Vary响应头,用来解决某些缓存服务的一个问题
  33. gzip_proxied any;
  34. gzip_comp_level 2;
  35. gzip_buffers 32 16k;
  36. # 默认 Nginx 只会针对 HTTP/1.1 及以上的请求才会启用 GZip,因为部分早期的 HTTP/1.0 客户端在处理 GZip 时有 Bug。现在基本上可以忽略这种情况,于是可以指定 gzip_http_version 1.0 来针对 HTTP/1.0 及以上的请求开启 GZip。
  37. gzip_http_version 1.0;
  38. gzip_min_length 250;
  39. gzip_types image/jpeg image/bmp image/svg+xml text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript image/x-icon;
  40. # brotli settings
  41. # brotli google开发的编码算法,比gzip高效20%;最适合静态文件
  42. brotli on;
  43. brotli_comp_level 4;
  44. brotli_buffers 32 8k;
  45. brotli_min_length 100;
  46. brotli_static on;
  47. brotli_types image/jpeg image/bmp image/svg+xml text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript image/x-icon;
  48. # Optimize session cache
  49. ssl_session_cache shared:SSL:50m;
  50. ssl_session_timeout 1d;
  51. # Enable session tickets
  52. ssl_session_tickets on;
  53. # OCSP Stapling
  54. ssl_stapling on;
  55. ssl_stapling_verify on;
  56. resolver 8.8.8.8 8.8.4.4 208.67.222.222 208.67.220.220 valid=60s;
  57. resolver_timeout 2s;
  58. # security headers
  59. # for HTTP Strict Transport Security HSTS
  60. # 防止 downgrade attacks https://en.wikipedia.org/wiki/Downgrade_attack
  61. add_header X-Frame-Options "SAMEORIGIN" always;
  62. add_header X-XSS-Protection "1; mode=block" always;
  63. add_header X-Content-Type-Options "nosniff" always;
  64. add_header Referrer-Policy "no-referrer-when-downgrade" always;
  65. add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;
  66. add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
  67. add_header X-Cache-Status $upstream_cache_status;
  68. # Logging Settings
  69. access_log /var/log/nginx/access.log;
  70. error_log /var/log/nginx/error.log;
  71. # limits
  72. limit_req_log_level warn;
  73. limit_req_zone $binary_remote_addr zone=reqlimit:10m rate=10r/m;
  74. limit_conn_zone $binary_remote_addr zone=connlimit:100m;
  75. limit_conn servers 1000; # Simultaneous Connections
  76. include /etc/nginx/conf.d/*.conf;
  77. include /etc/nginx/sites-enabled/*;
  78. }

针对域名配置

  1. proxy_cache_path /tmp/cacheapi levels=1:2 keys_zone=microcacheapi:100m max_size=1g inactive=1d use_temp_path=off;
  2. server {
  3. listen 443 ssl http2 default_server;
  4. listen [::]:443 ssl http2 default_server;
  5. server_name example.com;
  6. location /api/ {
  7. # Rate Limiting
  8. limit_req zone=reqlimit burst=20; # Max burst of request
  9. limit_req_status 460; # Status to send
  10. # Connections Limiting
  11. limit_conn connlimit 20; # Number ofdownloads per IP
  12. # Bandwidth Limiting
  13. limit_rate 4096k; # Speed limit (here is on kb/s)
  14. # Micro caching
  15. proxy_cache microcacheapi;
  16. proxy_cache_valid 200 1s;
  17. proxy_cache_use_stale updating;
  18. proxy_cache_background_update on;
  19. proxy_cache_lock on;
  20. proxy_pass http://localhost:8080;
  21. proxy_set_header X-Real-IP $remote_addr;
  22. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  23. proxy_set_header Host $http_host;
  24. proxy_set_header X-NginX-Proxy true;
  25. }
  26. location / {
  27. proxy_pass http://localhost:3000;
  28. proxy_set_header Host $host;
  29. proxy_set_header X-Real-IP $remote_addr;
  30. }
  31. location ~* \.(jpg|jpeg|png|gif|ico)$ { # client-side Caching
  32. expires 30d;
  33. }
  34. location ~* \.(css|js)$ { # client-side Caching
  35. expires 7d;
  36. }
  37. ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
  38. ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
  39. # Pagespeed Module
  40. pagespeed on;
  41. pagespeed FileCachePath /var/cache/ngx_pagespeed_cache;
  42. location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {
  43. add_header "" "";
  44. }
  45. location ~ "^/pagespeed_static/" { }
  46. location ~ "^/ngx_pagespeed_beacon$" { }
  47. pagespeed RewriteLevel PassThrough;
  48. pagespeed EnableCachePurge on;
  49. pagespeed PurgeMethod PURGE;
  50. pagespeed EnableFilters prioritize_critical_css;
  51. }
  52. server {
  53. listen 80;
  54. listen [::]:80;
  55. server_name example.com;
  56. return 301 https://$server_name$request_uri;
  57. }
  58. server {
  59. listen [::]:80;
  60. listen [::]:443 ssl;
  61. server_name www.example.com;
  62. return 301 https://example.com$request_uri;
  63. ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
  64. ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
  65. }

参考文章:

https://imququ.com/post/my-nginx-conf-for-wpo.html

https://medium.freecodecamp.org/powerful-ways-to-supercharge-your-nginx-server-and-improve-its-performance-a8afdbfde64d

http https

index 刷新方法

  1. $ curl baidu.com -vv
  2. * Rebuilt URL to: baidu.com/
  3. * Trying 220.181.57.217...
  4. * TCP_NODELAY set
  5. * Connected to baidu.com (220.181.57.217) port 80 (#0)
  6. > GET / HTTP/1.1
  7. > Host: baidu.com
  8. > User-Agent: curl/7.51.0
  9. > Accept: */*
  10. >
  11. < HTTP/1.1 200 OK
  12. < Date: Sat, 01 Apr 2017 06:32:35 GMT
  13. < Server: Apache
  14. < Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT
  15. < ETag: "51-47cf7e6ee8400"
  16. < Accept-Ranges: bytes
  17. < Content-Length: 81
  18. < Cache-Control: max-age=86400
  19. < Expires: Sun, 02 Apr 2017 06:32:35 GMT
  20. < Connection: Keep-Alive
  21. < Content-Type: text/html
  22. <
  23. <html>
  24. <meta http-equiv="refresh" content="0;url=http://www.baidu.com/">
  25. </html>
  26. * Curl_http_done: called premature == 0
  27. * Connection #0 to host baidu.com left intact

实现代码 example.cn.conf

  1. server {
  2. listen 80;
  3. server_name docs.lvrui.io;
  4. location / {
  5. # 将 index.html 文件放到下面的目录下
  6. root /var/www/html/refresh/;
  7. }
  8. }
  9. server {
  10. listen 443 ssl;
  11. server_name docs.lvrui.io;
  12. index index.html index.htm;
  13. access_log /var/log/nginx/docs.log main;
  14. ssl on;
  15. ssl_certificate /etc/ssl/docs.20150509.cn.crt;
  16. ssl_certificate_key /etc/ssl/docs.20150509.cn.key;
  17. error_page 404 /404.html;
  18. location / {
  19. root /var/www/html/docs;
  20. }
  21. }

uwsgi_pass 支持两种方法:

  • 直接读取对方建立的sock file
  • 直接使用socket传到指定的port(uwsgi会在那边监听)