I’m having a small problem with mod_rewrite
I have the following in my .htacces:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.+)\.htm$ index.php?name=$1 [NC]
This is my index.php file:
<?php echo $_GET['name']; ?>
This works great for the following url:
http://www.mySite.com/this is an example.htm
this would display “this is an example”
What i’m trying to do however, is get it to do the same, without the .htm extension:
for example:
http://www.mySite.com/this is an example
Any ideas?
(dont think it’s relevant but i’m using xampp to test this)
You can just make the extension optional in your rewrite rule:
Note that this is pretty much the equivalent of
which means that any URL other than going directly to http://www.mySite.com will redirect to index.php. If you have more specific rules, they should appear before this one.
Update: Like I was saying, this rule will match essentially all URLs on http://www.mySite.com — including index.php! Therefore, when you go to
www.mySite.com/this is an example, the following happens:^(.+)(\.htm)?$matches “this is an example”^(.+)(\.htm)?$matches “index.php”In order to prevent the second redirection (specifying [L], or last, doesn’t work, because after the first redirection rules are reapplied), you can use a RewriteCond to specify when to redirect:
This tells mod_rewrite to not apply the rule if the request URI (the part of the URL after the domain) starts with index.php.
You should take a look at the other rewrite conditions that you can specify. For example, you probably don’t want users to be redirected if they browse directly to another php file, either, so you can specify that in your
RewriteCondtoo:Which reads “if the request is not a file and the request is not index.php, redirect to index.php”.