In order to use mod_rewrite
you can type the following command in the terminal:
sudo a2enmod rewrite
Restart apache2 after
sudo /etc/init.d/apache2 restart
or
sudo service apache2 restart
or as per new unified System Control Way
sudo systemctl restart apache2
Then, if you'd like, you can use the following .htaccess
file.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
The above .htaccess
file (if placed in your DocumentRoot
) will redirect all traffic to an index.php
file in the DocumentRoot
unless the file exists.
So, let's say you have the following directory structure and httpdocs is the DocumentRoot
httpdocs/
.htaccess
index.php
images/
hello.png
js/
jquery.js
css/
style.css
includes/
app/
app.php
Any file that exists in httpdocs will be served to the requester using the .htaccess
shown above, however, everything else will be redirected to httpdocs/index.php
. Your application files in includes/app
will not be accessible.
Here's a .htaccess
file copied from the CodeIgniter PHP framework:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
This redirects everything that isn't index.php
, robots.txt
or anything in the images
folder to index.php/$1
, where $1
is the URL the user entered.
You need these rules as:
- Redirecting
index.php
would cause an infinte loop - http://localhost/index.php/index.php/index.php/...
robots.txt
is an important file that search engines use. It is just plain text; you don't want it handled by your code.
- You obviously want to keep having access to your images. Adjust this path as necessary for where your static assets are located.
Best Solution
Try this:
And to redirect direct requests of
/subfolder/…
:Or, even better, change your document root to that subfolder.