4
\$\begingroup\$

I have a Laravel 8 project hosted at xxx/laravel/ on an Apache server, where xxx is the domain. I want to serve the contents of xxx/laravel/public/ when users access xxx/laravel/. However, I need to prevent access to other files at xxx/laravel/, e.g. xxx/laravel/.env.

Normally, I would host the project files in directory outside the web directory (e.g. /home/projects/laravel instead of /var/www/html/laravel). I would then create a symlink from /home/projects/laravel/public to /var/www/html/laravel so that files such as .env are not accessible.

However, I need to store all the project files in the same place: /var/www/html/laravel.

I have found a potential solution which involved:

  • Copying /var/www/html/laravel/public/.htaccess to /var/www/html/laravel/.htaccess
  • Editing the new /var/www/html/laravel/.htaccess by:
    • Rewriting URLs using RewriteRule ^(.*)$ laravel/public/$1
    • Using server.php instead of index.php in the last rule, RewriteRule ^ server.php [L]
    • (Additionally) removing the -Indexes option

I followed some guidance from a similar question about using the existing public/ .htaccess. However, I did not create another index.php from a copy of server.php, and I made the above changes to prevent access to files.

Here is the modified /var/www/html/laravel/.htaccess (changes shown in comments with 'CHANGED').

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        # CHANGED: remove -Indexes
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # CHANGED: rewrite URLs to xxx/laravel/public
    RewriteRule ^(.*)$ laravel/public/$1

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    # CHANGED: use server.php instead of index.php
    RewriteRule ^ server.php [L]
</IfModule>

I know that this may still not be an optimal way of doing things, but given that I cannot use the typical method involving a symlink, I am unsure.

Is this method secure and reliable?

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.