htaccess remove index.php from url
The original answer is actually correct, but lacks explanation. I would like to add some explanations and modifications.
I suggest reading this short introduction https://httpd.apache.org/docs/2.4/rewrite/intro.html (15mins) and reference these 2 pages while reading.
https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html https://httpd.apache.org/docs/2.4/rewrite/flags.html
This is the basic rule to hide index.php
from the URL. Put this in your root .htaccess
file.
mod_rewrite
must be enabled with PHP and this will work for the PHP version higher than 5.2.6.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /index.php/$1 [L]
Think %{REQUEST_FILENAME}
as the the path after host.
E.g. https://www.example.com/index.html
, %{REQUEST_FILENAME}
is /index.html
So the last 3 lines means, if it's not a regular file !-f
and not a directory !-d
, then do the RewriteRule
.
As for RewriteRule formats:
So RewriteRule (.*) /index.php/$1 [L]
means, if the 2 RewriteCond
are satisfied, it (.*)
would match everything after the hostname. .
matches any single character , .*
matches any characters and (.*)
makes this a variables can be references with $1
, then replace with /index.php/$1
. The final effect is to add a preceding index.php
to the whole URL path.
E.g. for https://www.example.com/hello
, it would produce, https://www.example.com/index.php/hello
internally.
Another key problem is that this indeed solve the question. Internally, (I guess) it always need https://www.example.com/index.php/hello
, but with rewriting, you could visit the site without index.php
, apache adds that for you internally.
Btw, making an extra .htaccess
file is not very recommended by the Apache doc.
Rewriting is typically configured in the main server configuration setting (outside any
<Directory>
section) or inside<VirtualHost>
containers. This is the easiest way to do rewriting and is recommended
To remove index.php
from the URL, and to redirect the visitor to the non-index.php version of the page:
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]
This will cleanly redirect /index.php/myblog
to simply /myblog
.
Using a 301 redirect will preserve Google search engine rankings.
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)index\.php($|\ |\?)
RewriteRule ^ /%1 [R=301,L]