
I created the most awesome, the most unbelievable, the most dazzlingly shiny .htaccess
of all time for Laravel.
Alright, I’ll stop exaggerating, let’s get a bit serious so I can explain what problems it solves.
Aesthetic Problem
The default Laravel installation forces you to enter the public/
directory to run the application without using the CLI.
For example, to see the homepage you have to go here:
https://www.acitd.com/public/
Instead of here:
https://www.acitd.com/
Security Problem
Another little issue is that if you upload your app “as-is”, anyone can download the files located in the project’s root directory, something you definitely don’t want for security reasons.
What applications usually do is serve the contents of the public/
director as if they were in the root of the project /
, while all other files remain hidden.
Laravel also has another public directory: storage/app/public/
.
In case you didn’t know, here are the differences:
Directory | Usage |
---|---|
public/ |
You put static public files here, i.e., ones you create during development. |
storage/app/public/ |
Dynamic public files go here, i.e., ones created by the application (e.g., uploads). |
The Ultimate .htaccess Solution
To solve all the above issues, I’ve created the ultimate super-duper .htaccess
for Laravel.
Follow the steps below and you’ll be all set!
1. Place this .htaccess
file in the project’s root directory /
:
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{DOCUMENT_ROOT}/public%{REQUEST_URI} -d
RewriteRule ^ %{REQUEST_URI}/ [R=301,L]
RewriteCond %{REQUEST_URI} !^/storage/app/public/
RewriteCond %{DOCUMENT_ROOT}/storage/app/public%{REQUEST_URI} -f
RewriteRule ^ /storage/app/public%{REQUEST_URI} [QSA,L]
RewriteCond %{REQUEST_URI} !^/(public|storage/app/public)/
RewriteRule ^ /public%{REQUEST_URI} [QSA,L]
2. Place this .htaccess
file inside the storage/app/public/
directory:
storage/app/public/.htaccess
allow from all
That’s it!
Now the only public directoris are the ones below, and their files appear as if they’re located in the root /:
public/
storage/app/public/
Also, you got rid of that annoying public/ in the URL!
BTW: The files you want to protect shouldn’t be cached so that .htaccess
can be applied.
So that’s it… now go take a dip since summer’s here :D
Written by: Human
Translated by: AI