When deploying a Laravel application on shared hosting, you may encounter the common issue of the “public” folder appearing in your website’s URL. This can make your URLs less elegant and user-friendly. In this tutorial, we’ll explore two effective solutions to remove “public” from the URL in Laravel 10.
Table of Contents
Why Remove ‘Public’ from Laravel URL?
Before we dive into the solutions, it’s essential to understand why we need to remove “public” from the Laravel URL. When you upload a Laravel application to shared hosting, you often can’t set the path directly to the index.php
file. As a result, you must run the application from the “public” folder, which can lead to URLs like yourwebsite.com/public/index.php
. This is far from ideal, and we’ll show you how to clean it up.
Solution 1: Removing ‘Public’ Using .htaccess
In Laravel, the .htaccess
file plays a crucial role in URL rewriting and can be used to eliminate “public” from your URLs. Follow these steps:
- Create a New
.htaccess
File: Go to the root folder of your Laravel application and create a new.htaccess
file. - Edit
.htaccess
: Open the newly created.htaccess
file and add the following code:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
- Save and Upload: Save the changes and upload the
.htaccess
file to the root directory of your Laravel application.
This .htaccess
code uses Apache’s mod_rewrite
module to redirect all requests to the “public” folder, effectively removing “public” from the URL.
Solution 2: Rename server.php and Move .htaccess
To further clean up your Laravel URLs, follow these steps:
- Rename
server.php
: In your Laravel root folder, rename theserver.php
file toindex.php
. - Move
.htaccess
: Locate the.htaccess
file within the/public
directory of your Laravel application. Copy it and paste it into your Laravel root folder. - Move Assets: If your application has CSS and JS files in the “public” folder, move them to the root folder as well. Be sure to update the references to these assets in your views and layouts.
These steps effectively route all incoming requests to the index.php
file and streamline your URLs.
Conclusion
Removing “public” from your Laravel 10 application’s URL is a crucial step to make your website URLs more user-friendly. You can choose between using a .htaccess
file or renaming files and moving the .htaccess
for achieving this goal. By following these solutions, your Laravel application will have cleaner, more professional-looking URLs, improving user experience and SEO rankings.