I will write down the setting method to display the static files (css and images) of the Django project correctly in EC2 (Amazon Linux2) + Apache environment as a reminder.
The method of displaying static files differs between the Django development server and the Web server such as Apache. First, rewrite the contents of settings.py as follows.
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static') #For production
# STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] #For development
After that, execute the following command to aggregate the static files under each application into the static folder directly under the project.
$ python3 manage.py collectstatic
Next, create an Apache configuration file under /etc/httpd/conf.d/. Here, it is created with the name "myproject.conf".
Execute the following command to edit the configuration file.
sudo vi /etc/httpd/conf.d/myproject.conf
myproject.conf
LoadModule wsgi_module /usr/local/lib64/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so
ServerName <List the public IP address of EC2>
WSGIScriptAlias / /home/ec2-user/myproject/myproject/wsgi.py
WSGIPythonPath /home/ec2-user/myproject:/usr/bin/python3
<Directory /home/ec2-user/myproject/myproject>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
Alias /static/ /home/ec2-user/myproject/static/
<Directory /home/ec2-user/myproject/static>
Require all granted
</Directory>
Lines 1-12 are for associating Apache with mod_wsgi. The 14th and subsequent lines are the description to allow static folders.
Finally restart Apache.
sudo service httpd restart
The static file should now be displayed correctly.
Recommended Posts