Laravel comes with default server for local environment and but if run the application in apache
then we need to remove the public from URL because if we serve the application through the Apache then we need to call the URLs from public directory. It can be multiple way to remove the public from URL in laravel but most efficient and recommended way to remove is using virtual host and pointing virtual host to public directory of application.
We will cover all possible wat to achieve it and this example we will work in all laravel version laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9
There is multiple options to remove the public from the URL in laravel application.
let’s have look on multiple options of removing public and which one is more secure and reliable method to use.
1. Replacing server.php to index.php
Replacing the root file server.php to index.php is easiest way to remove public from url. but this is not safe and recommended method.
you also need to copy the public/.htaccess
file to root folder of the website to working it out.
2. Creating a .htaccess file on root of laravel project
Creating a new file on root of laravel .htaccess
and put this below code in the file
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L,QSA]
This code will rewrite all request to public folder silently and application will not expose to security risk.
3. Best and recommended method by laravel, creating virtual host to remove public from URL
To enable this we need to edit the apache
httpd.conf or httpd-vhost.conf file.
And enter the below code to enable virtual host for the specific application.
<VirtualHost *:80>
DocumentRoot "F:/xampp/htdocs/dev/public"
ServerAdmin admin@localhost
ServerName laravel.app
ServerAlias www.laravel.app
<Directory "F:/xampp/htdocs/laravelblog/public">
AllowOverride All
Options Indexes FollowSymLinks
Require local
# if you want access from other pc's on your local network
#Require ip 192.168.1
# Only if you want the world to see your site
#Require all granted
</Directory>
</VirtualHost>