第17章 附录
setting 常用设置
官方地址: https://docs.djangoproject.com/zh-hans/2.0/ref/settings/
DATABASES
默认值: 空字典 {},包含要与django一起使用的所有数据库的设置的字典。是一个嵌套字段,其内容将数据库别名映射到包含单个数据选项的字典。
该DATABAES必须设置default数据库,还可以指定任意数量的其他附加的数据库
# sqlite3DATABASES = {'default': {'ENGINE': 'django.db.backends.sqlite3','NAME': 'mydatabase',}}# postgresqlDATABASES = {'default': {'ENGINE': 'django.db.backends.postgresql','NAME': 'mydatabase','USER': 'mydatabaseuser','PASSWORD': 'mypassword','HOST': '127.0.0.1','PORT': '5432',}}
可以使用以下内部选项来进行更复杂的配置:
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。
upstream backend { # backend 上游服务器组名字server backend1.example.com weight=5;server backend2.example.com:8080;server unix:/tmp/backend3;server backup1.example.com:8080 backup;server backup2.example.com:8080 backup;}server {location / {proxy_pass http://backend;}}
location语法
location [=|~|~*|^~] pattern {}# = 精确匹配# ^~ 以某个常规字符串开头,不是正则匹配# ~ 区分大小写的正则匹配# ~* 不区分大小写的正则匹配# / 通用匹配,匹配所有
规则解释:
location = 精确匹配 > location 完整路径 > location ^~ 路径 > location ~,~* 正则顺序 > location 部分起始路径 > location /# location ^~ 路径 # 以某个字符串开头,不是正则匹配location = / {proxy_pass http://tomcat:8080/index}location ^~ /static/ {root /webroot/static/;}location / {proxy_pass http://tomcat:8080/;}
location配置优先级
- 普通匹配与顺序无关,因为按照匹配的长短来取匹配结果。
- 正则匹配与顺序有关,因为是从上往下匹配。(首先匹配,取其之。结束解析过程)
nginx conf 配置参考
- http重定向到https
# the upstream component nginx needs to connect toupstream django {#server unix:///tmp/uwsgi.sock;#server unix:/tmp/uwsgi.sock;#server 192.168.0.152:8080; # for a web port socket (we'll use this first)server 127.0.0.1:8080; # for a web port socket (we'll use this first)}# http site confserver {listen 80;server_name 192.168.0.152;charset utf-8;# max upload sizeclient_max_body_size 75M; # adjust to taste# Django medialocation /media {alias /srv/WEME_BE/weme/media/;}location /static {alias /srv/WEME_BE/weme/static/;}location /xadmin {proxy_pass http://127.0.0.1:8080/xadmin;}location /api/v1 {proxy_pass http://127.0.0.1:8080;}location / {if ($request_method = 'OPTIONS') {add_header 'Access-Control-Allow-Origin' '*';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';add_header 'Access-Control-Max-Age' 1728000;add_header 'Content-Type' 'text/plain; charset=utf-8';add_header 'Content-Length' 0;return 204;}root /srv/weme_http/;index index.html index.htm;}}# configuration of the server# https site confserver {# the port your site will be served onlisten 443 ssl;server_name 192.168.0.152; # substitute your machine's IP address or FQDNcharset utf-8;ssl on;ssl_certificate /etc/nginx/ssl/192.168.0.152.crt;ssl_certificate_key /etc/nginx/ssl/192.168.0.152.key;proxy_request_buffering off;proxy_buffering off;proxy_connect_timeout 75s;proxy_read_timeout 300s;# max upload sizeclient_max_body_size 75M; # adjust to taste# Django medialocation /media {alias /srv/WEME_BE/weme/media/; # your Django project's media files - amend as required}location /static {alias /srv/WEME_BE/weme/static/; # your Django project's static files - amend as required}location /xadmin {proxy_pass http://127.0.0.1:8080/xadmin;}location /api/v1 {proxy_pass http://127.0.0.1:8080;}location / {if ($request_method = 'OPTIONS') {add_header 'Access-Control-Allow-Origin' '*';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';add_header 'Access-Control-Max-Age' 1728000;add_header 'Content-Type' 'text/plain; charset=utf-8';add_header 'Content-Length' 0;return 204;}root /srv/weme/;index index.html index.htm;}}
需要根据站点配置做相应修改
# /etc/nginx/conf.d/mysite_nginx.conf# the upstream component nginx needs to connect toupstream django {# server unix:///path/to/your/mysite/mysite.sock; # for a file socketserver 127.0.0.1:8001; # for a web port socket (we'll use this first)}# configuration of the serverserver {# the port your site will be served onlisten 80;# the domain name it will serve forserver_name .example.com; # substitute your machine's IP address or FQDNcharset utf-8;# max upload sizeclient_max_body_size 75M; # adjust to taste# Django medialocation /media {alias /path/to/your/mysite/media; # your Django project's media files - amend as required}location /static {alias /path/to/your/mysite/static_dist; # your Django project's static files - amend as required}# Finally, send all non-media requests to the Django server.location / {uwsgi_pass django; # go to [upstream django]include /etc/nginx/uwsgi_params; # the uwsgi_params file you installed}}
项目实例1 - uwsgi
upstream django {server 127.0.0.1:3031;}server {listen 80;#server_name .example.com;server_name 192.168.0.130;client_max_body_size 75M;charset utf-8;#access_log /var/log/nginx/ebee_access.log;error_log /var/log/nginx/ebee_error.log;location /media {alias /var/www/ebee/static/media/;}location /static {alias /var/www/ebee/static/;}# Finally, send all non-media requests to the Django server.location / {uwsgi_pass django;#include /var/www/ebee/ebee/uwsgi_params;include /etc/nginx/uwsgi_params;}}
错误信息很好理解,就是说 Access-Control-Allow-Origin 有两个值,但是浏览器只准许有一个值,所以报错。
增强nginx性能方法
优化代码逻辑的极限是移除所有逻辑;
优化请求的极限是不发送任何请求。
这两点通过缓存都可以实现。
项目实例
# vim /etc/nginx/nginx.confuser www-data;worker_processes auto;pid /run/nginx.pid;events {worker_connections 768;# multi_accept on;}http {# Basic Settings# sendfile 提高 Nginx 静态资源托管效率。sendfile 是一个系统调用,直接在内核空间完成文件发送,不需要先 read 再 write,没有上下文切换开销。sendfile on;# socket选项,只有在启用了 sendfile 之后才生效;启用它之后,数据包会累计到一定大小之后才会发送,减小了额外开销,提高网络效率。tcp_nopush on;tcp_nodelay on; # socket选项,启用后禁用 Nagle 算法keepalive_timeout 65;types_hash_max_size 2048;server_tokens off;# server_names_hash_bucket_size 64;# server_name_in_redirect off;include /etc/nginx/mime.types;default_type application/octet-stream;# SSL Settingsssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLEssl_prefer_server_ciphers on;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$# gzip settingsgzip on;# gizp_disable 接受一个正则表达式,当请求头中的UserAgent满足这个正则时,响应不会启用gzip# 特别地,指令值 msie6 等价于 MSIE [4-6]\.,但性能更好一些。gzip_disable "msie6";gzip_vary on; # 输出Vary响应头,用来解决某些缓存服务的一个问题gzip_proxied any;gzip_comp_level 2;gzip_buffers 32 16k;# 默认 Nginx 只会针对 HTTP/1.1 及以上的请求才会启用 GZip,因为部分早期的 HTTP/1.0 客户端在处理 GZip 时有 Bug。现在基本上可以忽略这种情况,于是可以指定 gzip_http_version 1.0 来针对 HTTP/1.0 及以上的请求开启 GZip。gzip_http_version 1.0;gzip_min_length 250;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;# brotli settings# brotli google开发的编码算法,比gzip高效20%;最适合静态文件brotli on;brotli_comp_level 4;brotli_buffers 32 8k;brotli_min_length 100;brotli_static on;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;# Optimize session cachessl_session_cache shared:SSL:50m;ssl_session_timeout 1d;# Enable session ticketsssl_session_tickets on;# OCSP Staplingssl_stapling on;ssl_stapling_verify on;resolver 8.8.8.8 8.8.4.4 208.67.222.222 208.67.220.220 valid=60s;resolver_timeout 2s;# security headers# for HTTP Strict Transport Security HSTS# 防止 downgrade attacks https://en.wikipedia.org/wiki/Downgrade_attackadd_header X-Frame-Options "SAMEORIGIN" always;add_header X-XSS-Protection "1; mode=block" always;add_header X-Content-Type-Options "nosniff" always;add_header Referrer-Policy "no-referrer-when-downgrade" always;add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;add_header X-Cache-Status $upstream_cache_status;# Logging Settingsaccess_log /var/log/nginx/access.log;error_log /var/log/nginx/error.log;# limitslimit_req_log_level warn;limit_req_zone $binary_remote_addr zone=reqlimit:10m rate=10r/m;limit_conn_zone $binary_remote_addr zone=connlimit:100m;limit_conn servers 1000; # Simultaneous Connectionsinclude /etc/nginx/conf.d/*.conf;include /etc/nginx/sites-enabled/*;}
针对域名配置
proxy_cache_path /tmp/cacheapi levels=1:2 keys_zone=microcacheapi:100m max_size=1g inactive=1d use_temp_path=off;server {listen 443 ssl http2 default_server;listen [::]:443 ssl http2 default_server;server_name example.com;location /api/ {# Rate Limitinglimit_req zone=reqlimit burst=20; # Max burst of requestlimit_req_status 460; # Status to send# Connections Limitinglimit_conn connlimit 20; # Number ofdownloads per IP# Bandwidth Limitinglimit_rate 4096k; # Speed limit (here is on kb/s)# Micro cachingproxy_cache microcacheapi;proxy_cache_valid 200 1s;proxy_cache_use_stale updating;proxy_cache_background_update on;proxy_cache_lock on;proxy_pass http://localhost:8080;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_set_header X-NginX-Proxy true;}location / {proxy_pass http://localhost:3000;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}location ~* \.(jpg|jpeg|png|gif|ico)$ { # client-side Cachingexpires 30d;}location ~* \.(css|js)$ { # client-side Cachingexpires 7d;}ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbotssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot# Pagespeed Modulepagespeed on;pagespeed FileCachePath /var/cache/ngx_pagespeed_cache;location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {add_header "" "";}location ~ "^/pagespeed_static/" { }location ~ "^/ngx_pagespeed_beacon$" { }pagespeed RewriteLevel PassThrough;pagespeed EnableCachePurge on;pagespeed PurgeMethod PURGE;pagespeed EnableFilters prioritize_critical_css;}server {listen 80;listen [::]:80;server_name example.com;return 301 https://$server_name$request_uri;}server {listen [::]:80;listen [::]:443 ssl;server_name www.example.com;return 301 https://example.com$request_uri;ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbotssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot}
参考文章:
https://imququ.com/post/my-nginx-conf-for-wpo.html
http https
index 刷新方法
$ curl baidu.com -vv* Rebuilt URL to: baidu.com/* Trying 220.181.57.217...* TCP_NODELAY set* Connected to baidu.com (220.181.57.217) port 80 (#0)> GET / HTTP/1.1> Host: baidu.com> User-Agent: curl/7.51.0> Accept: */*>< HTTP/1.1 200 OK< Date: Sat, 01 Apr 2017 06:32:35 GMT< Server: Apache< Last-Modified: Tue, 12 Jan 2010 13:48:00 GMT< ETag: "51-47cf7e6ee8400"< Accept-Ranges: bytes< Content-Length: 81< Cache-Control: max-age=86400< Expires: Sun, 02 Apr 2017 06:32:35 GMT< Connection: Keep-Alive< Content-Type: text/html<<html><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></html>* Curl_http_done: called premature == 0* Connection #0 to host baidu.com left intact
实现代码 example.cn.conf
server {listen 80;server_name docs.lvrui.io;location / {# 将 index.html 文件放到下面的目录下root /var/www/html/refresh/;}}server {listen 443 ssl;server_name docs.lvrui.io;index index.html index.htm;access_log /var/log/nginx/docs.log main;ssl on;ssl_certificate /etc/ssl/docs.20150509.cn.crt;ssl_certificate_key /etc/ssl/docs.20150509.cn.key;error_page 404 /404.html;location / {root /var/www/html/docs;}}
uwsgi_pass 支持两种方法:
- 直接读取对方建立的
sock file - 直接使用socket传到指定的
port(uwsgi会在那边监听)
