Problem with MOD REWRITE (.htm and .php files)

Hi,

I am using this MOD REWRITE:

RewriteEngine On
RewriteRule ^tutorials/([^/\\.]+)/?$ tutorials.php?id=$1 [L]

But it does not work.

My site has mainly (about 10) .htm files. And 1 .php file.

The problem is when the MOD REWRITE comes into effect if the user then clicks to go to any other page the MOD REWRITE causes a problem. It still thinks I want to MOD REWRITE when the user clicks to view a .htm file!

What is going wrong?

Matt.

By itself, mod_rewrite doesn’t check if files exist, unless you tell it to. Which you can do by using RewriteCond and %{REQUEST_FILENAME}, like so


RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^tutorials/([^/\\.]+)/?$ tutorials.php?id=$1 [L]

This means, if (RewriteCond) the requested URL (%{REQUEST_FILENAME}) is not an existing file (!-f), then apply the RewriteRule. Otherwise don’t apply the RewriteRule.

The problem is still there with your code.

If the user clicks:

tutorials/a/ there are really visiting tutorials.php?letter=a

but if THEY NEXT click on contact.htm they are sent to:

tutorials/a/contact.htm

whereas I just want them to go to:

contact.htm

Why is the MOD REWRITE code not working?

That is not a mod_rewrite problem, that’s a problem in your HTML.

Instead of <a href=“contact.html”>contact</a> you must do <a href=“/contact.html”>contact</a>

thanks - yes that it working now. Can you help with one further thing please?

How do I add .htm to the end of the URL that appears online?

currently I have “tutorials/a” as the URL I enter into my pages and then the MOD REWRITE does its work in the background (as you know).

If I write tutorials/a.htm then it will be trying to load tutorials.php?letter=a.htm which would be wrong.

Any ideas?

Matt.

I have just noticed the code has caused a problem:

In this code in the page:

if(preg_match('#^[a-z]{1}$#i', $_GET['letter'])) {
    $letter = strtolower($_GET['letter']); // valid input
}else{
    $letter = 'a'; // default value for invalid input
}  

it is always choosing the letter ‘a’ (for an invalid input)

Has the MOD REWRITE caused a problem with the GET part of my coding??

Matt.

I have solved the problem. But I still keen to get a the link with .htm after it, if you know how?

Sure, just change it to

 
RewriteRule ^tutorials/([^\\.]+)\\.htm$ tutorials.php?id=$1 [L]

Or even better, since you just want to accept a through z:

 
RewriteRule ^tutorials/([a-z])\\.htm$ tutorials.php?id=$1 [L]

Thanks - I’ve used the A-Z one.

if there is number in url then it could be

RewriteRule ^tutorials/([a-z][0-9])\\.htm$ tutorials.php?id=$1 [L]

That would match any letter plus a digit, like a1, b2, c9, d4, etc.
If you’d like to match any letter or digit (which is not the case here I don’t think), you’d use

RewriteRule ^tutorials/([a-z0-9])\\.htm$ tutorials.php?id=$1 [L]