user2076817
user2076817

Reputation: 3

Converting PHP preg_replace to htaccess rewrite

I need to create a 301 redirect rule that will match/replace underscores _ with dashes - and remove the trailing .html. The URLs could have any number of underscores _ which is making this difficult for me.

In PHP I can do this as such:

$subject = 'this_is_a_bad_url.html';    
$pattern = array('/(_)/', '/.html/');
$replace = array('-', '');
$output = preg_replace($pattern, $replace, $subject);
//$output would result to 'this-is-a-bad-url'

How would I write this in .htaccess?

Thanks for the help.

Upvotes: 0

Views: 1075

Answers (1)

mohammad mohsenipur
mohammad mohsenipur

Reputation: 3149

try this

  Options +FollowSymLinks -MultiViews
  RewriteEngine on
  RewriteCond %{REQUEST_URI} ^(.*?)_(.*?)$ [NC]
  RewriteRule ^  /%1-%2 [R,L]
  RewriteCond %{REQUEST_URI} ^(.*?).html$ [NC]
  RewriteRule ^  /%1 [R,L]

Upvotes: 1

Related Questions