我有一个子域为:app.example.com
现在,我想在app.example.com上提供一个静态网站,该网站在Django应用程序上进行一些基于API的查询,而我希望将它们托管在相同的基本URL上,例如:app.example.com/app/api.。 ..
但是我无法这样做。我的Nginx配置如下:
server {
root /home/ubuntu/dist/;
index index.html index.htm index.nginx-debian.html;
server_name app.example.com;
location / {
alias /home/ubuntu/dist/ ;
try_files $uri /$uri index.html last;
}
location /admind {
alias /home/ubuntu/admind/dist/ ;
try_files $uri /$uri/ index.html last;
}
location /app/ {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://gunicorn;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
# listen 80;
# listen [::]:80;
#
# server_name example.com;
#
# root /var/www/example.com;
# index index.html;
#
# location / {
# try_files $uri $uri/ =404;
# }
#}
server {
if ($host = app.example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 default_server;
listen [::]:80 default_server;
server_name app.example.com;
return 404; # managed by Certbot
}
每当我实施以下配置时,app.example.com都会按预期打开,但是Django应用url app.example.com/app/api或与此相关的Django Admin的/ app / admin /不会打开并抛出404。 TIA
答案 0 :(得分:2)
您如何将BASE_URL
附加到所有核心url_patterns
,类似,
settings.py
BASE_URl = 'app/'
urls.py
from django.conf import settings
from django.urls import path
from .views import *
urlpatterns = [
path("%sadmin/" % settings.BASE_URL, AdminView, name='admin'),
path("%sapi/" % settings.BASE_URL, MyAPIView, name="myapi"),
]
通过这种方式,您所有的URL都已经以app /开头,因此,即使您反向代理根app.example.com
,它仍然可以在app/
上投放
答案 1 :(得分:0)
您需要添加标头以告知Django您正在通过子路径进行服务。
location /app/ {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header SCRIPT_NAME app;
proxy_redirect off;
proxy_pass http://gunicorn;
}