Django部署AWS EC2后跳转index.html出现404错误求助
问题情况
主页面加载正常,但点击跳转按钮时触发404错误,本地开发环境运行无异常,部署到AWS EC2(搭配nginx和gunicorn)后出现故障。
错误详情
Request Method: GET
Request URL: http://18.222.182.68/index.html
Using the URLconf defined in LectureLingo.urls, Django tried these URL patterns, in this order:[name='index']
admin/
The current path, index.html, didn’t match any of these.You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
核心原因
你的Django路由配置中没有index.html这个路径,仅配置了空路径('')和index/路径。本地开发时可能因为服务器特性或静态文件存在能正常访问,但部署后Django严格匹配路由,因此触发404。
解决步骤
1. 修正JavaScript跳转目标
将主页面JS中的window.location.href = 'index.html';改为匹配Django路由的路径:
- 直接修改为
window.location.href = 'index/'; - 更规范的做法是用Django模板反向解析URL:
在主HTML文件的<script>标签前添加:
然后JS中改为:<script> const indexUrl = "{% url 'index' %}"; </script>
这种方式能适配不同部署环境的URL结构,避免硬编码出错。window.location.href = indexUrl;
2. 确认路由配置正确性
检查transcript/urls.py中的path('index/', views.index_view, name='index'),是否正确,主urls.py是否已正确包含该应用的路由配置。
3. 检查Nginx配置(可选)
若问题仍存在,确保Nginx未将index.html当作静态文件处理,需将所有非静态请求转发给gunicorn,示例配置:
location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } location /static/ { alias /path/to/your/project/static/; }
相关代码参考
views.py
def index_view(request): return render(request, 'index.html')
transcript/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.index_view, name='home'), path('index/', views.index_view, name='index'), ]
项目主urls.py
from django.conf.urls import include from django.contrib import admin from django.urls import path urlpatterns = [ path('', include('transcript.urls')), path('admin/', admin.site.urls), ]
修改后的主页面JavaScript
document.querySelector('#sendButton').onclick = function() { var dropdownFrom = document.getElementById('dropdown1').value; var dropdownTo = document.getElementById('dropdown2').value; if (dropdownFrom !== "" && dropdownTo !== "") { websocket.send(JSON.stringify({ 'dropdown1': dropdownFrom, 'dropdown2': dropdownTo })); localStorage.setItem('detectedLanguage', dropdownTo); window.location.href = indexUrl; } else { alert('请选择两个下拉菜单的选项。'); } };
内容的提问来源于stack exchange,提问作者Katoo

