Django 403 error for static files on shared hosting using passenger_wsgi
I'm trying to get my Django app running on a shared hosting site using passenger_wsgi (following the instruction of the hosting provider).
Since the app is for the main domain I installed it using this folder layout:
public_html
django
static
css
js
images
SMC_website
templates
In settings.py I have:
STATIC_URL = 'static/'
STATICFILES_DIRS = [
'/home/xxxxxx/public_html/django/static/',
'/home/xxxxxx/public_html/django/static/css',
'/home/xxxxxx/public_html/django/static/js',
'/home/xxxxxx/public_html/django/static/images',
]
In urls.py I have:
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r"^$", views.index, name="Home Page"),
]
urlpatterns += static(settings.STATIC_URL,
document_root=os.path.join(settings.BASE_DIR, 'static'))
When I try out the "static(settings.STATIC_URL,document_root=os.path.join(settings.BASE_DIR, 'static'))" in the django manage.py shell I get a an empty list ([]). Not sure why, or if this is the cause of my problem.
The app runs, pulls data from the database, but generates a 403 error for any content accessed from the static folders (css, js, or images).
I have these folder permisisons:
drwxr-x--- 2 xxxxxx xxxxxx 4096 Dec 17 18:30 css
drwxr-x--- 8 xxxxxx xxxxxx 4096 Dec 17 18:30 images
drwxr-x--- 3 xxxxxx xxxxxx 4096 Dec 17 18:30 js
drwxr-xr-x 5 xxxxxx xxxxxx 4096 Dec 11 14:24 SMC_website
drwxr-xr-x 3 xxxxxx xxxxxx 4096 Dec 11 14:24 logs
-rw-r--r-- 1 xxxxxx xxxxxx 689 Dec 11 14:24 manage.py
-rw-r--r-- 1 xxxxxx xxxxxx 1442 Dec 17 18:08 passenger_wsgi.py
-rw-r--r-- 1 xxxxxx xxxxxx 245760 Dec 11 14:24 smcDB.sqlite3
drwxr-xr-x 10 xxxxxx xxxxxx 4096 Dec 11 14:31 static
the xxxxxx is the User Name and it is the same as the folder in settings.py above
In the Browser debugger I see the expected urls for the static content, e.g:
<script type="text/javascript" src="https://southmetrochorale.org/static/js/smc.js"></script>
Any suggestion on how to resolve this 403 error?
Okay, first you need to specify your STATIC_ROOT
within settings.py
. This declares the folder where you want to serve your static-files from.
Then you do the command python manage.py collectstatic
. This pulls all your static-files from your STATICFILES_DIRS
and organizes them inside the folder you declared under STATIC_ROOT
before.
This part:
urlpatterns += static(settings.STATIC_URL,
document_root=os.path.join(settings.BASE_DIR, 'static'))
is only working within the django-testserver thing with DEBUG=True
.
The problem you are facing is the production versus development.
For further reading I recommend How to deploy static files in production
I found the solution to this problem. Because the Django app is in a folder (django) in the main domain location (public_html) -> public_html/django and the static folder is at public_html/django/static I needed to use: STATIC_URL = "django/static/"
All is well, all static files are now being served.