Laravel部署报错:symlink()因安全原因被禁用,求助解决方法
Hey there! That symlink error popping up only on first load is a super common gotcha with Laravel on shared hosting—let’s walk through exactly how to fix it, and why it’s happening in the first place.
Why This Happens
Laravel tries to automatically create a symbolic link between public/storage and storage/app/public (this is where your uploaded files like images or PDFs live) during its initial setup or first request. Most shared hosts disable the symlink() function for security reasons, so this attempt fails and throws the error. Once you refresh, Laravel doesn’t try to create the link again, hence the error disappears—but your public file access might still be broken behind the scenes.
Solutions to Try
1. Manually Create the Symbolic Link (Recommended if Possible)
If your host lets you access SSH or has a file manager with symlink support (like cPanel), this is the cleanest fix:
- With SSH: Navigate to your Laravel project root and run:
Double-check the paths match your setup—if your public folder is in a different location (likeln -s ../storage/app/public public/storagepublic_html), adjust accordingly. - With cPanel File Manager:
- Go to your
public(orpublic_html) directory - Click "New File" > Select "Symbolic Link"
- For the "Link Target", enter
../storage/app/public - Name the link
storageand save
- Go to your
2. Disable Automatic Symlink Creation
If you can’t create a symlink manually, tweak Laravel to stop trying to make one:
Open app/Providers/AppServiceProvider.php and update the boot() method to check if the storage link exists, and skip creating it (or copy files instead):
public function boot() { // Skip symlink creation if it's disabled $publicStoragePath = public_path('storage'); if (!file_exists($publicStoragePath)) { // Optional: Copy the storage/public directory to public instead of linking // \Illuminate\Support\Facades\File::copyDirectory(storage_path('app/public'), $publicStoragePath); } }
3. Bypass the Symlink Entirely
Another workaround is to adjust Laravel’s filesystem config to point directly to the storage folder, no link needed:
Open config/filesystems.php and modify the public disk configuration:
'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/storage', 'visibility' => 'public', ],
This tells Laravel to serve public files directly from storage/app/public instead of expecting a symlink in the public folder. Just make sure your web server has read access to the storage/app/public directory.
Quick Note on the "Refresh Fix"
The error disappearing after a refresh doesn’t mean the problem is solved—it just means Laravel stops attempting to create the symlink on subsequent requests. You’ll still run into issues when trying to access uploaded files until you implement one of the fixes above.
内容的提问来源于stack exchange,提问作者Andreea Ilie

