Remove public from URL in Laravel

Remove public keyword from url using .htaccess file

Working with Laravel application when we render our url we always see public keyword in our url by default. Here are some ways to get rid of that public keyword from url. Let’s take a look at it.

1) Using Virtual Host on Apache Web Server

If your application has an apache web server and you have root access of your server then you can remove public keyword from URL using Virtual Host. Code as shown below

<VirtualHost *:80>
        ServerAdmin info@example.com
        ServerName example.com
        ServerAlias www.example.com
        DocumentRoot /var/www/html/{yoursourcedirectory}/public

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

2) Create .htaccess file in root directory

If your application runs with Apache web server but you don’t have your server access via ssh then you need to copy your .htaccess file placed under public to root and make the following changes in .htaccess file which you recently placed under root directory.

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} -d [OR]
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^ ^$1 [N]

    RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
    RewriteRule ^(.*)$ public/$1 

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ server.php

</IfModule>

3) Change in Directory structure

There are also some couple of ways to remove public keyword from URL. See one more way as below

  • Rename server.php in your Laravel root folder to index.php
  • Copy the .htaccess file from /public directory to your Laravel root folder.

Leave a Reply

Your email address will not be published. Required fields are marked *