skip to Main Content

I have a Laravel project which was moved from custom VPS into shared hosting.

Rewrite all from root to the public was easy part.

But when i go to the domain.com/public page works…

So how i rewrite domain root to the public, but redirect direct acces to the domain.com/public back to the domain.com/ ?

Disclaimer:
There is plenty threads about Laravel and rewrite to the public folder. But no one works as expected.

2

Answers


  1. Chosen as BEST ANSWER

    I found solution so i want to share it with others.

    
    <IfModule mod_rewrite.c>
    # That was ONLY to protect you from 500 errors
    # if your server did not have mod_rewrite enabled
    
    
        RewriteEngine On
    
        # Handle Authorization Header
        RewriteCond %{HTTP:Authorization} .
        RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    
        # Prevent direct access to the "public" folder - redirect to root
        RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /public/
        RewriteRule ^public/(.*) /$1 [R=302,L]
    
        #RewriteRule ^public/(.*)$ /$1 [R=302,L]
    
    
        # Redirect Trailing Slashes If Not A Folder...
        # - but look for the file in the "public" folder
        #   (ensure we are not already in the "public" folder)
        RewriteCond %{REQUEST_URI} !^/public/
        RewriteCond %{DOCUMENT_ROOT}/public/$1 !-d
        RewriteRule ^(.*)/$ /$1 [R=302,L]
    
        # Rewrite "everything" to the "public" subdirectory if not already
        # This ignores existing files/dirs in the document root
        RewriteCond %{REQUEST_URI} ^/(.*)
        RewriteRule !^public/ public/%1 
    
        # Handle Front Controller... (as before)
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.php [L]
    
    
    </IfModule>
    

  2. Because most shared hosts do not let you change the directory of the main domain, this is a common problem. With Laravel, you must point the domain to the public folder.

    While it is possible, be aware that with this solution you would be playing whack-a-mole with security issues were the app to ever update, as noted by @Tpojka you might be at risk of leaking secrets such as from your .env file.

    A better solution which was described in this answer is to move the Laravel app directory somewhere else and either copy or symlink the public/ folder contents. This way the app’s actual files are not publicly accessible. You will need to make sure if you need to symlink storage/ that you move it to the proper document root as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search