Question

I am building a clean url system using .htaccess and php. The main idea is to rewrite everything to index.php and to split the url to segments separated by /. It works but when I upload it to web server I get an infinite loop error.

My .htaccess file is:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]

If I get things correctly - the problem is that it redirects index.php to itself but it shouldn't because I have index.php file that handles everything and RewriteCond %{REQUEST_FILENAME} !-f which should prevent that rewrite.

Could you please help me with this .htaccess - I want it to rewrite everything to index.php and to be as portable as it can be, so I can use it in:

www.mysite.com www.myothersite.com

or even www.mysite.com/new/

I also want to redirect something like www.mysite.com/articles/2 to index.php as well as www.mysite.com/articles/it/2 or even www.mysite.com/articles/it/search/searchterm

Was it helpful?

Solution

Here's code taken from Drupal's .htaccess which uses the "clean urls" approach you are trying to achieve.

# Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

In this case, it appends the clean URL as the "q" querystring parameter. So then your script can detect what content to deliver based on $_GET['q'].

And here's another approach, this one from Wordpress.

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

This one specifically looks for requests to index.php and filters them out before doing the redirection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top