When developing a Laravel application, you may notice that the default URL structure includes the /public directory. This happens because Laravel’s entry point, the index.php file, is located inside the public folder. However, exposing this structure is not ideal for security and user-friendly URLs. In this guide, we will show you how to remove public from the URL using an .htaccess file.
Why Remove /public from the URL?
Cleaner URLs – A professional and user-friendly URL should not contain unnecessary directory names.
Security – Exposing internal folder structures could be a security risk.
Better Deployment – Most hosting providers expect the application to run from the root directory, not
/public.
Steps to Remove public from URL
1. Move .htaccess to the Root Directory
By default, Laravel includes an .htaccess file inside the public folder. You need to move it to the root directory of your Laravel project.
Navigate to your Laravel project.
Move the
.htaccessfile frompublic/.htaccessto the root directory.
2. Modify .htaccess in the Root Directory
Create or edit the .htaccess file in the root directory and add the following code:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>This rule ensures that all requests are redirected to the public directory internally while keeping the URL clean.
3. Update server.php
Laravel includes a server.php file that acts as an entry point for built-in PHP development servers. Modify this file to redirect all requests to public/index.php:
Open
server.phpin the root directory.Replace the existing code with:
<?php
require_once __DIR__.'/public/index.php';4. Configure Virtual Host (For Apache Servers)
If you have access to Apache’s virtual host configuration, you can define the document root as public to avoid the need for an .htaccess rule.
Edit your Apache configuration file and set up a virtual host:
<VirtualHost *:80>
ServerName yourdomain.com
DocumentRoot /var/www/html/your-laravel-project/public
<Directory /var/www/html/your-laravel-project>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>Restart Apache for the changes to take effect:
sudo service apache2 restartConclusion
Removing public from your Laravel project’s URL improves the aesthetics, security, and deployment process. By configuring .htaccess and adjusting server settings, you ensure that your application runs smoothly while keeping URLs clean and professional.
If you need expert Laravel development or deployment support, feel free to reach out. Our team specializes in building optimized and secure Laravel applications!