生产环境有时,并不是为了一个项目而存在的。毕竟,域名是比较稀有的。
今天遇到这个问题,解决了。作个记录。
并且,如果将django项目部署在Nginx后面,那如何获取用户真实的IP地址呢?
下面就来解决吧。
一,gunicorn.ini的编写
bind = "127.0.0.1:xxxx" workers = 4 errorlog = './gunicorn.error.log' accesslog = './gunicorn.access.log' timeout = 3000 loglevel = 'debug' proc_name = 'gunicorn_proc' access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"' daemon = True worker_connections = 1000 max_requests = 2000 graceful_timeout = 300 #loglevel = 'info'
二,nginx配置
location /abc/ {
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;
proxy_pass http://127.0.0.1:xxxx;
}
location ^~ /abc/static {
alias /xxx/abc/static;
}
三,顺便,启停gunicorn的命令
gunicorn -c gunicorn.ini acsctl.wsgi pkill -9 gunicorn
四,settings.py文件更改(注意DEBUG关闭及ALLOW_HOSTS打开)
STATIC_URL = '/abc/static/' LOGIN_URL = '/abc/accounts/login/'
五,urls.py里,记得带上子目录前缀
。。。。 path('abc/accounts/login/', user_login, name='login'), 。。。。
六,获得用户浏览器真实IP
try: real_ip = self.request.META['HTTP_X_FORWARDED_FOR'] if len(real_ip) > 1: ip = real_ip.split(",")[0] except Exception as e: try: ip = self.request.META['REMOTE_ADDR'] except Exception as e: ip = "0.0.0.0"