我如何成功提供静态文件和媒体文件?与 django 一起
要使用 Nginx 在 Django 中成功提供静态和媒体文件,
您需要配置 Django 的设置和 Nginx。具体方法如下:
配置 Django 设置: 在您的 settings.py 中,确保正确配置了以下设置:
# settings.py
# Define the URL prefix for static files.
STATIC_URL = '/static/'
# Define the directory where Django will collect static files during deployment.
STATIC_ROOT = '/staticfiles/'
# Define the URL prefix for media files.
MEDIA_URL = '/media/'
# Define the directory where uploaded media files will be stored.
MEDIA_ROOT = '/path/to/your/media/directory'
收集静态文件: 在部署 Django 项目之前,请确保通过运行以下命令来收集静态文件:
python manage.py collectstatic
配置Nginx: 接下来,您需要配置 Nginx 来提供静态文件和媒体文件。这是 Nginx 配置示例:
navigate to the editable configuration of your project
# /etc/nginx/sites-available/your_project_name
server {
listen 80;
server_name your_domain.com;
location /static/ {
alias /path/to/your/static/directory/;
}
location /media/ {
alias /path/to/your/media/directory/;
}
location / {
include proxy_params;
proxy_pass http://unix:/run/gunicorn.sock;
}
}
Make sure to replace your_domain.com with your actual domain and /path/to/your/static/directory/ and /path/to/your/media/directory/ with the paths to your static and media directories respectively.
链接Nginx配置: 配置 Nginx 后,在站点启用目录中创建指向 Nginx 配置文件的符号链接:
sudo ln -s /etc/nginx/sites-available/yourproject /etc/nginx/sites-enabled/
希望这个视频也有帮助 希望这个视频有帮助