Moving the public directory outside of the main Laravel project directory is not a common practice and is not necessary for security if you configure your web server correctly. Laravel is designed to protect your application code by serving requests through the public directory, which acts as the document root. All other directories are not directly accessible via the web server.
However, if you have a specific reason to move the public directory, you can do so by updating your server configuration and Laravel's paths. Here's how you can achieve that:
- Update your web server configuration to point to the new public directory. For example, if you're using Nginx, you would update the
rootdirective in your site's configuration file:
server {
listen 80;
server_name example.com;
root /var/www/public;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# ... other configurations for PHP, etc.
}
- In your Laravel application, you need to update the
bootstrap/app.phpfile to set the public path. You've already added the line, but make sure it's correct:
$app->usePublicPath(base_path('../public'));
Make sure the path you provide to base_path() is the correct relative path from your bootstrap directory to the new public directory.
- After moving the
publicdirectory, you should also update thepublic_path()helper function. You can do this by adding a new method in theAppServiceProvider:
// In app/Providers/AppServiceProvider.php
public function register()
{
$this->app->bind('path.public', function() {
return base_path('../public');
});
}
-
If you have assets that use the
asset()helper, they should continue to work as long as thepublic_path()function returns the correct path. -
You do not need to delete the original
publicfolder inside your project folder, but you should ensure that it is not accessible via the web server. You can rename it or remove it if you're sure that all assets and references have been updated accordingly.
Remember to clear the config cache after making these changes:
php artisan config:clear
And finally, always test your changes in a development or staging environment before deploying to production to ensure that everything works as expected.