Hendra ~
Dec 23, 2024
239
Technology
When deploying a Laravel application to a shared hosting environment, especially when you need to serve images or other assets stored in Laravel's storage directory, it's common to encounter issues with file accessibility. This is typically because the public directory in Laravel needs to be mapped correctly with the public_html directory used by most shared hosting services.
Here’s a step-by-step guide to restructuring your Laravel project to work correctly on shared hosting, particularly for serving images and other assets stored in the storage directory:
# Step 1: Modify the Directory Structure
- Move Laravel's Public Directory Files to public_html
- Move all the contents of the public directory in your Laravel project to the public_html directory on your hosting.
- This includes the index.php file and any assets you have directly in the public directory.
- Update the index.php File
# Step 2: Link Storage Directory
Laravel uses the storage/app/public directory to store publicly accessible files, including images. You need to create a symbolic link from public_html/storage to storage/app/public. However, on many shared hostings, you may not be able to use the php artisan storage:link command directly.
- Create the Symbolic Link Manually via SSH (if available)
Replace /path/to/laravel/ and /path/to/public_html/ with the actual paths on your server.
ln -s /path/to/laravel/storage/app/public /path/to/public_html/storage
# Step 3: Configure Filesystems
Adjust the config/filesystems.php to ensure the public disk uses the correct root path. And Make sure the APP_URL in your .env file reflects the actual URL of your application.
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
# Step 4: Use Asset URLs
When generating URLs for your stored images or files, make sure to use the asset or Storage facade in your Laravel files:
$url = asset('storage/file.txt'); // Using the `asset` helper
// Or using the Storage facade
$url = Storage::url('file.txt');
# Conclusion
This setup ensures that your images and assets stored in Laravel's storage directory are accessible via the public_html directory in a shared hosting environment. Always remember to secure your application by removing any temporary scripts used for configuration after they are no longer needed. Additionally, regularly back up your application and database, and monitor the security configurations of your hosting environment.