403 error in AWS Lightsail in Nginx
Resolving the nginx 403 issue on AWS Lightsail while accessing Media Files
Published on July 17, 2024
When hosting a Django project on AWS LightSail using Nginx and Gunicorn, you might encounter permission issues. Here are two effective methods to resolve these issues.
Method 1: Modify Nginx Configuration and Permissions
-
Navigate to your project directory:
cd /path/to/your/project
-
Change permissions for the media directory:
chmod -R 777 media
-
Update the Nginx configuration in
/etc/nginx/sites-available/your_project
:Change from:
location /static/ {
root /home/username/project;
}
location /media/ {
root /home/username/project;
}To:
location /static/ {
alias /home/username/project/static/;
}
location /media/ {
alias /home/username/project/media/;
} -
Reload your service files and restart Nginx and Gunicorn:
sudo systemctl restart nginx
sudo service gunicorn restart
sudo service nginx restart
Method 2: Create and Configure a New Media Directory
-
Create a new directory for media files in
/var/www/your_project/media/
:sudo mkdir -pv /var/www/your_project/media/
-
Change the permissions of the new media folder:
Replace
user_name
with your actual username, which you can find using thewhoami
command.sudo chown -cR user_name:user_name /var/www/your_project/media
-
Update the routes in
settings.py
:Replace the existing
MEDIA_URL
andMEDIA_ROOT
with:MEDIA_URL = '/var/www/your_project/media/'
MEDIA_ROOT = '/var/www/your_project/media'
Conclusion
By following either of these methods, you can resolve permission issues when hosting a Django project on AWS LightSail with Nginx and Gunicorn. Choose the method that best fits your project’s structure and requirements. Restarting the necessary services ensures that changes take effect, allowing your project to run smoothly. If you enjoyed my article, show your appreciation with a round of applause! 👏 Your support means the world to me! Feel free to connect with me across various social media channels! Join me on LinkedIn, GitHub, and PeerList. Your support means a lot. Thanks for taking the time to read this