# Media File Fix - Deployment Guide

## Problem Summary
Media files return 404 errors in production even though they exist, but work when `DEBUG = True`.

## Root Cause
Django doesn't serve media files in production by default, and web server configuration wasn't properly handling media file requests.

## Complete Solution Applied

### 1. Fixed .htaccess File
- **Issue**: Was using `/media/` instead of `media/` (relative path)
- **Fix**: Changed to use relative path `media/$1`

### 2. Added Django URL Serving (Fallback)
- **Issue**: Django URLs only served media files in development
- **Fix**: Removed `if settings.DEBUG:` condition

### 3. Added MediaFileMiddleware (Primary Solution)
- **Issue**: No Django-level handling of media files in production
- **Fix**: Created middleware that intercepts media requests and serves files securely

## Files Modified

### Core Files:
1. **`.htaccess`** - Fixed media file path
2. **`branch_system/urls.py`** - Removed DEBUG condition for media serving
3. **`utils/middleware.py`** - Added MediaFileMiddleware
4. **`branch_system/settings_production.py`** - Added middleware to production settings

### Test Files:
5. **`test_media_access.py`** - Test script to verify media access
6. **`deploy_media_fix.sh`** - Deployment script

## Deployment Steps

### Step 1: Upload Modified Files
Upload these files to your production server:
```bash
# Core files
.htaccess
branch_system/urls.py
utils/middleware.py
branch_system/settings_production.py

# Test files
test_media_access.py
deploy_media_fix.sh
```

### Step 2: Run Deployment Script
```bash
chmod +x deploy_media_fix.sh
./deploy_media_fix.sh
```

### Step 3: Test Media Access
```bash
python test_media_access.py
```

### Step 4: Restart Application
```bash
# Touch restart file for Passenger
touch tmp/restart.txt

# Or restart web server
sudo systemctl restart apache2
```

## Verification

### Test 1: Direct File Access
Try accessing a media file directly:
```
https://branchbusinessadvance.co.ke/media/kyc/id_documents/WhatsApp_Image_2024-10-22_at_14.06.10.jpeg
```

### Test 2: Application Access
Check if media files load in your Django application.

### Test 3: Check Logs
```bash
# Django logs
tail -f logs/django.log

# Apache logs
sudo tail -f /var/log/apache2/error.log
```

## How the Solution Works

### Layer 1: .htaccess (Web Server Level)
- Apache tries to serve media files directly
- If file exists, serves it immediately
- If not, passes to Django

### Layer 2: Django URLs (Application Level)
- Django's URL patterns catch media requests
- Serves files using `static()` function
- Works as fallback if .htaccess fails

### Layer 3: MediaFileMiddleware (Django Level)
- Intercepts all `/media/` requests
- Performs security checks
- Serves files with proper headers
- Handles authentication for KYC documents

## Security Features

### MediaFileMiddleware Security:
1. **Path Validation**: Prevents directory traversal attacks
2. **File Existence Check**: Ensures files exist before serving
3. **Content Type Detection**: Sets proper MIME types
4. **Authentication Check**: Requires login for KYC documents
5. **Boundary Check**: Ensures files are within MEDIA_ROOT

## Troubleshooting

### If Files Still Don't Load:

1. **Check File Permissions**:
   ```bash
   ls -la media/
   sudo chmod -R 755 media/
   sudo chown -R www-data:www-data media/
   ```

2. **Check Django Settings**:
   ```bash
   python manage.py shell
   >>> from django.conf import settings
   >>> print(settings.MEDIA_ROOT)
   >>> print(settings.MEDIA_URL)
   ```

3. **Test Middleware**:
   ```bash
   python test_media_access.py
   ```

4. **Check Web Server Logs**:
   ```bash
   sudo tail -f /var/log/apache2/error.log
   ```

### Common Issues:

1. **500 Server Error**: Check if middleware is properly imported
2. **Permission Denied**: Check file permissions and ownership
3. **File Not Found**: Verify file paths and MEDIA_ROOT setting
4. **Slow Loading**: Consider using CDN for better performance

## Performance Considerations

### Current Setup:
- Files served directly by Apache (fastest)
- Django middleware as fallback
- Basic caching headers

### Future Improvements:
1. **CDN Integration**: Use Cloudflare or AWS S3
2. **Image Optimization**: Compress images automatically
3. **Caching**: Implement Redis caching for frequently accessed files
4. **Load Balancing**: Distribute media files across multiple servers

## Monitoring

### Add Logging to Middleware:
```python
import logging
logger = logging.getLogger(__name__)

# In serve_media_file method
logger.info(f"Media file served: {file_path} by user: {request.user}")
```

### Monitor File Access:
- Track which files are accessed most
- Monitor for unauthorized access attempts
- Log performance metrics

## Success Criteria

The fix is successful when:
1. ✅ Media files load in production with `DEBUG = False`
2. ✅ Files are accessible directly via URL
3. ✅ Files load properly in Django templates
4. ✅ Security checks prevent unauthorized access
5. ✅ Performance is acceptable

## Rollback Plan

If issues occur, you can:
1. Remove `MediaFileMiddleware` from settings
2. Revert `.htaccess` changes
3. Set `DEBUG = True` temporarily
4. Use Django's built-in development server for media files

## Next Steps

1. **Deploy the fixes**
2. **Test thoroughly**
3. **Monitor for issues**
4. **Consider CDN implementation**
5. **Set up proper monitoring** 