3.1 KiB
3.1 KiB
Mixed Content Fix - HTTPS Image URLs
Problem
When the site is served over HTTPS (via ngrok), images from Strapi using HTTP URLs (http://160.187.167.213/uploads/...) were blocked by browsers due to Mixed Content security policies. This caused:
- Missing images
- Layout shifts (CLS - Cumulative Layout Shift)
- Poor user experience
Solution
Created a utility function ensureHttpsImageUrl() that automatically converts HTTP image URLs to HTTPS when the site is served over HTTPS.
Implementation
New Utility Function (lib/utils.ts):
- Detects if the site is served over HTTPS (checks
window.location.protocol) - Automatically converts HTTP URLs to HTTPS
- Handles relative URLs, absolute URLs, and protocol-relative URLs
- Works seamlessly in both development and production
Updated Components
All components that load images from Strapi now use the utility function:
- ✅ navbar.tsx - Logo images
- ✅ testimonials.tsx - Avatar images
- ✅ trusted-by.tsx - Trusted school logos
- ✅ footer.tsx - Footer logo
How It Works
// Before (caused Mixed Content errors):
const imageUrl = `http://160.187.167.213${url}`
// After (automatically uses HTTPS when needed):
const imageUrl = ensureHttpsImageUrl(url)
The function:
- Checks if the current page is served over HTTPS
- If yes, converts any HTTP URLs to HTTPS
- If no, keeps the original protocol
- Handles all URL formats (relative, absolute, protocol-relative)
Benefits
- No More Mixed Content Errors: Images load correctly when site is served over HTTPS
- No Layout Shifts: Images load properly, preventing CLS issues
- Automatic Detection: Works automatically without manual configuration
- Backward Compatible: Still works with HTTP in development
- Centralized Logic: All image URL handling in one place
Testing
To test the fix:
-
Local Development (HTTP):
npm run dev # Images should load normally with HTTP URLs -
Ngrok (HTTPS):
ngrok http 3000 # Access via ngrok HTTPS URL # Images should automatically use HTTPS URLs -
Production (HTTPS):
- Deploy to production with HTTPS
- Images will automatically use HTTPS
Browser Console
Before the fix, you would see:
Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure image 'http://160.187.167.213/uploads/...'. This content should also be served over HTTPS.
After the fix:
- No Mixed Content warnings
- All images load correctly
- No console errors
Notes
- The utility function only converts HTTP to HTTPS when the site itself is served over HTTPS
- In development (HTTP), images will still use HTTP (no conversion needed)
- The function is safe to use everywhere image URLs are constructed
- It handles edge cases like protocol-relative URLs (
//example.com)
Future Improvements
If Strapi is ever configured to serve images over HTTPS directly, you can:
- Update
NEXT_PUBLIC_STRAPI_BASE_URLto use HTTPS - The utility function will still work correctly
- Or remove the utility function if all URLs are already HTTPS