我的堆栈是 Django-Rest-Framework,前端是 Vue.js。所有这些都在 Google Cloud 的一个实例上运行(至少在我尝试实现 SSL 之前它是运行的),其中 nginx 用作 Web 服务器,Gunicorn 运行 Django 后端。
目前得到的错误如下:
xhr.js:178 GET https://example.com:8000/api/.../.../ net::ERR_TIMED_OUT
这是我的 nginx.conf(在/etc/nginx/sites-available/example.com.conf
):
server {
listen 80;
server_name *.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 443 default_server ssl;
server_name example.com;
ssl_certificate /etc/ssl/private/ssl-bundle.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_session_cache shared:SSL:20m;
ssl_session_timeout 60m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
location / {
alias /path/to/project/;
try_files $uri $uri/ /index.html;
}
location /dist/ {
root /path/to/project;
}
location ^~ /(api|rest-auth|admin)/ {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_pass https://0.0.0.0:8000;
}
}
我正在使用 axios 发出 xhr 请求,以下是与此问题相关的标头配置:
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
axios.defaults.baseURL = 'https://example.com:8000'
一些可能相关的 Django 设置:
ALLOWED_HOSTS =['www.example.com','example.com','127.0.0.1']
CORS_ORIGIN_ALLOW_ALL=True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
CSRF_COOKIE_SECURE = True
我遇到的另一个问题是,从 http 到 https 的域名转发似乎不起作用(即我必须输入https://example.com查看网站)。
答案1
如果有人想知道,这不是防火墙问题。我最终通过对 nginx 配置和其他一些事情进行了一些调整,让它正常工作了。在这里发布,以防有人像我一样偶然发现这一点。
Django 配置
ALLOWED_HOSTS = ['.example.co']
axios 配置
axios.defaults.baseURL = 'https://example.co'
nginx.conf
upstream django-api {
server 127.0.0.1:8000;
}
server {
listen 80;
server_name .example.com;
return 301 https://example.co$request_uri;
}
server {
gzip on;
listen 443 default_server ssl;
server_name example.co;
add_header Strict-Transport-Security "max-age=31536000"; include
SubDomains" always;
ssl_certificate /etc/ssl/private/ssl-bundle.crt;
ssl_certificate_key /etc/ssl/private/example.co.key;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:20m;
ssl_session_timeout 60m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
location / {
alias /path/to/project/;
try_files $uri $uri/ /index.html;
}
location /dist/ {
root /path/to/project/;
}
location /api/ {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_pass http://django-api;
}
location /rest-auth/ {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_pass http://django-api;
}
}