Mind bending .htaccess / pretty-url problem

software development

#1

Hey Folks,

I’m running into a mind-bending .htaccess situation and would sure appreciate some help!

Here’s the problem:

I’m creating “pretty URLs” for many pages using .htaccess lines like this:

RewriteRule example1.html /example.php?n=1 [NC]

These work. So far so good. But then I start thinking, gosh it would be even prettier to drop the .html altogether, and just have url.com/example be the link. Plain and simple.

So I start trying to implement it, and, it mostly works, but fails in an interesting way.

You can see it fail by visiting www.bhaktibreakfastclub.com/example2.

I’ve got this line in .htaccess which is doing its job:
RewriteRule example2 /example.php?n=2 [NC]

HOWEVER: In the html on my pages, often “example2” is also used as part of an image or video file name. Such as, in this case, “example2_check.jpg”

Now the image doesn’t show up, because it sees the “example2” part of the filename and tries to replace that with /example.php?n=2…

SO! What to do? I want it to do that substitution for the initial URL, but not for the subsequent image or video components of that page… And I do need to continue using filenames that include the same name as the page they’re on, as in “example2_check.jpg”.

Thanks!
~Daniel


#2

#3

Gorgeous, works perfect. Thanks bobocat!
~Daniel


#4

[quote=“danielct, post:1, topic:59025”]I’ve got this line in .htaccess which is doing its job:
RewriteRule example2 /example.php?n=2 [NC]

I want it to do that substitution for the initial URL, but not for the subsequent image or video components of that page… And I do need to continue using filenames that include the same name as the page they’re on, as in “example2_check.jpg”.[/quote]

Use some “only if file not exist” rules (conditions) so that if any files or directories DO exist then they are not rewritten by your regex.

RewriteEngine On RewriteCond %{SCRIPT_FILENAME} !-d RewriteCond %{SCRIPT_FILENAME} !-f RewriteRule ^example(.*)$ /example.php?n=$1 [NC]


#5

Update: Played around with patterns, per sXi and bobocat. Dang they are convenient! Now I’m using:

RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^example([0-9]+)$ /example.php?n=$1 [NC]

Thanks you guys,
~Daniel


#6

Can I upvote this thread for OP coming back to report on the final solution?