All Django deployments (web or REST frameworks) require a setup for serving static files, and most of the time it causes trouble. It requires 3-4 steps to make it work properly:
- Set to Django project settings.py
- Set into Nginx configuration file
- Collect all static files
- (Optional) Move static files
1. Set to Django project settings.py
The default and most tutorials recommend the following configuration in the project’s settings.py
STATIC_URL = "static/"
import os
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
For this example, we use the same configuration.
Note: We assume you have nginx already set up and running. For this example, nginx is running on EC2 in AWS.
2. Set up Nginx configuration file
In the Nginx server settings section, you will have the following (or similar, depending on the path to /static) configuration to serve static files.
Note: It is recommended to place the static folder in a location controlled by Ngnix, there will be no problems. For example, /var/www/
location /static/ {
root /var/www/PROJECT_NAME;
}
3. Collect all static files
To collect static files, execute the following command:
$python manage.py collectstatic
The output of collectstatic depends on the path given in step 1.
Therefore, the output will be stored in the project root directory.
4. (Optional) Move static files
This step is optional if the paths to collectstatic and nginx configurations are the same. Otherwise, we need to move the /static folder to /var/www/PROJECT_NAME (this tutorial will follow this).
- Create a project folder in /var/www/ (requires root permissions, so use sudo) var/www$sudo mkdir project_name
- Move static from project to /var/www/project_name project_name/$ sudo mv -r static/ /var/www/project_name
and your static files should work. Restart Gunicorn and Ngnix for the changes to take effect.