Drew
Drew

Reputation: 6872

htaccess Rewrite Rule

I use htaccess to rewrite my URL's so here is what I have:

RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?page=$1 [L]

So if I go to domain.com/services then it works perfect, but what I want to do is make it so if they do type in domain.com/services.php then it will work instead of not being found.

Also.. if I go to domain.com/services/ (with a trailing slash) then it acts like it's not found. Why is this?

Upvotes: 1

Views: 3754

Answers (4)

LazyOne
LazyOne

Reputation: 165473

You have limited "rewrite loop" (limited to 2 iterations only). Use these rules:

# do not do anything for already existing files
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]

RewriteRule ^([a-z0-9_\-]+)(\.php)?$ index.php?page=$1 [NC,L,QSA]

If you do not like it, here is an alternative (but I still prefer #1, but maybe this one will be better for your setup/app logic -- this assumes that index.php is located in website root folder):

RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule ^([a-z0-9_\-]+)(\.php)?$ index.php?page=$1 [NC,L,QSA]

Upvotes: 3

Adam MacDonald
Adam MacDonald

Reputation: 1958

This should work for you:

RewriteRule ^([a-zA-Z0-9_-]+) index.php?page=$1 [L]

You aren't allowing a period, so the '.php' fails the expression since it is terminated with $

Upvotes: 0

genesis
genesis

Reputation: 50982

RewriteRule ^([a-zA-Z0-9_-]+)\.php$ index.php?page=$1 [L]
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?page=$1 [L]
RewriteRule ^([a-zA-Z0-9_-]+)\/$ index.php?page=$1 [L]

add slash as aceptable possible character (note ^([a-zA-Z0-9_-]+)\/$)

Upvotes: 0

Fabio
Fabio

Reputation: 19216

For the second requirement (the php extension) try this

RewriteRule ^([a-zA-Z0-9_-]+)(\.php)?$ index.php?page=$1 [L]

untested, but it should work.

Upvotes: 0

Related Questions