我正在尝试将 Django/React 应用程序部署到 AWS。我遇到服务器未获取静态文件的问题。我想我已经正确配置了所有内容,但没有显示任何内容。我不确定我是否遗漏了一个步骤,因为它似乎在 PythonAnywhere 而非 AWS 上正常工作。
这是我的settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
我运行 python manage.py collectstatic 将我的文件生成到根目录。它输出 复制到 '/home/ubuntu/test/test/static' 的静态文件。
我在控制台得到的错误如下 GET http://ec2-18-217-253-182.us-east-2.compute.amazonaws.com:5000/static/assets/vendor/bootstrap/css/bootstrap.min.css net::ERR_ABORTED 404(未找到)
我希望有人遇到过同样的问题,因为 SO 上的其他几个解决方案都没有解决这个问题。这是当前的文件结构
test/
├── test/
├── frontend/
└── static/
请您参考如下方法:
你用过 Create React App 吗?如果是这样,您将必须配置 your PUBLIC_URL指向正确的文件夹。
因为我不知道你确切的 Django 设置,这里有一些其他的事情需要考虑:
正确的 URL(2.1 语法)
urlpatterns += [
re_path(r'(?P<path>.*)', TemplateView.as_view(template_name='index.html'), name='home')
]
更正静态文件 URL:
# Static files (CSS, JavaScript, Images)
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'media'
BASE_DIR = Path(__file__).resolve().parent.parent
STATICFILES_DIRS = [BASE_DIR.parent / 'build' / 'static']
正确的 S3 存储桶配置:
# utils.py
from storages.backends.s3boto3 import S3Boto3Storage
def StaticRootS3BotoStorage(): return S3Boto3Storage(location='static')
def MediaRootS3BotoStorage(): return S3Boto3Storage(location='media')
和
# conf.py
import os
from django.core.exceptions import ImproperlyConfigured
def get_env_variable(var_name):
"""Get the environment variable or return exception."""
try:
return os.environ[var_name]
except KeyError:
error_msg = 'Set the {} environment variable'.format(var_name)
raise ImproperlyConfigured(error_msg)
AWS_ACCESS_KEY_ID = get_env_variable("ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = get_env_variable("SECRET_ACCESS_KEY")
AWS_S3_SIGNATURE_VERSION = 's3v4'
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_STORAGE_BUCKET_NAME = get_env_variable("AWS_BUCKET_NAME")
AWS_S3_CUSTOM_DOMAIN = '%s.s3.eu-central-1.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_LOCATION = 'static'
STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
STATICFILES_STORAGE = 'config.settings.aws.utils.StaticRootS3BotoStorage'
DEFAULT_FILE_STORAGE = 'config.settings.aws.utils.MediaRootS3BotoStorage'
MEDIA_URL = 'https://%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME
MEDIA_ROOT = MEDIA_URL
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
作为引用,这是我使用的文件夹设置(以防您遇到路径问题)。 aws 内部是 conf.py 和 utils.py。
