Link to home
Start Free TrialLog in
Avatar of Adam Jones
Adam Jones

asked on

RewriteRule to Include HTML, but Not Affect Images

Hello

I am having problems with a rewrite rule and could do with some assistance.

I wanted to forward all _ in the URL to - (so example.com/this_page.html would forward to example.com/this-page.html)

I have set this up fine with

RewriteRule (.*)_(.*) $1-$2 [R=301,L] 

Open in new window


the problem is that this is also forwarding images and I do not want this.

I have tried

RewriteCond %{REQUEST_FILENAME} \.(gif|png|jpg|ico|swf)$ [NC]
RewriteRule (.*)_(.*) $1-$2 [R=301,L]  

Open in new window


I am only learning about RewriteRule so are not sure the best way to do this. I think I would like it only if ends in .html but some of my pages have variables (like page_1.html?sort=p.viewed&order=DESC) so will this still work?

Any Advice will be very appreciated.

Thanks
Adam
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

It's common for web developers to put JavaScript, CSS, and images into separate sub-directories, below the web root.  Are your files organized this way?  If so, you should be able to impose the RewriteRule on the directories that contain the HTML and leave the other directories alone.
ASKER CERTIFIED SOLUTION
Avatar of Steve Bink
Steve Bink
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>> Regexp are greedy, so your first (.*) will eat the whole line,

Yes and no.  The regex will try hardest to match the unqualified '_' character.  So, in a filename with only one underscore, it should come out just fine.  In a name with two underscores, you'll probably get something like:
example_page_name.htm
$1 = example_page
$2 = name.htm

Open in new window


As a technical matter, arober11 is correct, but the actual behavior is slightly different..