我有一个网站,它使用Django作为API和Vue作为前端。目前,当我部署站点时,我执行以下操作:
- 创建 Vue 应用程序的生产版本 (
npm run build
( - 将 Vue
dist
文件夹复制到 Django 应用程序中的特定文件夹中 - 其中一个 Django url 被设置为一个提供 Vue
index.html
的TemplateView
通过执行上述操作,生产中的Nginx
只需使用gunicorn
提供 Django 应用程序,一切正常。
但是,我更愿意让 Nginx 提供 Vueindex.html
和静态文件。例如,/
将服务于 Django 应用程序,/spa
将服务于 Vue 应用程序,而 Vue 应用程序本身将调用 api。
这是我当前的Nginx
配置:
upstream appserver_wsgi_app {
server localhost:8000 fail_timeout=0;
}
server {
listen 80;
server_name www.example.com;
rewrite ^(.*) https://$server_name$1 permanent;
}
server {
server_name www.example.com;
listen 443 ssl;
...
...
...
location /static {
autoindex on;
alias /home/user/static_django_files/;
}
location /media {
autoindex on;
alias /home/user/media_django_files/;
}
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
if (!-f $request-filename) {
proxy_pass http://appserver_wsgi_app;
break;
}
}
}
Nginx
需要更改哪些内容,以便它服务于Vue index.html
和static files
以及Django
应用程序?另外,Vue 端是否需要更改任何内容,因为 im 目前只是按如下方式调用 api:
axios.post("/api/dosomething/", data)
编辑
我已经将以下内容添加到我的nginx配置中,并上传了Vue dist文件夹:
location /spa {
autoindex on;
alias /path/to/dist/;
try_files $uri $uri/ /index.html;
}
我还在vue.config.js
中添加了以下内容:
baseUrl: '/spa'
对我Vue Router
:mode: history
重新启动 nginx 时,vue 应用程序的index.html
页面尝试在浏览器中加载,但它找不到它试图在以下位置查找的css
和js
文件:
www.example.com/spa/js/...
www.example.com/spa/css/...
我有一个类似的设置,我在端口8090上使用uwsgi运行Django REST后端,并通过nginx为angular 4前端的生产构建提供服务。这是我的nginx.conf
server {
listen 80;
server_name **url**;
rewrite ^ https:// **url** $request_uri? permanent;
}
server {
listen 443 ssl;
server_name **url**;
ssl_certificate **.pem;
ssl_certificate_key **.key;
root *path to your vue production build folder where index.html resides*;
index index.html;
error_page 502 /gateway.html;
location /assests {
autoindex on;
alias *path to you Django assets *;
}
location /static {
autoindex on;
alias *path to you static files both django static files and vue related static files*;
}
// this to server the django admin
location /manage/ {
proxy_pass http://127.0.0.1:8090/manage/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
// this is for the REST backend
location /api/{
proxy_pass http://127.0.0.1:8090;
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_set_header X-Forwarded-Proto $scheme;
}
}
我认为类似的设置应该适用于 Django + Vue.js 项目。让我知道它是否有效。
**编辑 对于您的第二个问题,在nginx.conf中使用"/spa/static"创建另一个位置,类似于"/static"。