Reputation: 11
I have problem in my URL.
This is my code in htaccess:
RewriteRule ^music-(.*)-([0-9_]+)\.html$ /artiste.php?g=$1&page=$2 [NC,L]
So some URL on Google or Bing could be showing like this music_(.*)_([0-9_]+)\.html
If possible I want to change _
to -
with htaccess.
I want any url with _
to change to -
, because all links work correct with -
but in my research some URLs have _
so I want to replace them with -
.
example:
Error : http://www.example.com/me_like_this.html Correct : http://www.example.com/me-like-this.html
Upvotes: 1
Views: 136
Reputation: 9007
You can use the following in your /.htaccess
file:
RewriteEngine On
# Replace underscores with hyphens, set the environment variable,
# and restart the rewriting process. This essentially loops
# until all underscores have been converted to hyphens.
RewriteRule ^([^_]*)_(.*)$ $1-$2 [E=underscore:yes,N]
# Then, once that is done, check if the underscore variable has
# been set and, if so, redirect to the new URI. This process ensures
# that the URI is rewritten in a loop *internally* so as to avoid
# multiple browser redirects.
RewriteCond %{ENV:underscore} yes
RewriteRule (.*) /$1 [R=302,L]
Then add your rule afterwards:
RewriteRule ^music-(.+)-(\d+).html$ /artiste.php?g=$1&page=$2 [NC,L]
If this is working for you, and you would like to make the redirects cached by browsers and search engines, change 302
to 301
.
Note: In your
RewriteRule
I have changed.*
to.+
so it only matches one or more characters, instead of zero or more characters. Additionally, I have changed[0-9_]+
to\d+
, which is the shorthand equivalent without including underscores, which would be converted to hyphens anyway. If you want to include hyphens in the last capture group, then change(\d+)
to([\d-]+)
.
Upvotes: 1
Reputation: 2132
RewriteEngine On
RewriteRule ^(.*)_(.*)$ /$1-$2 [L,R=301]
RewriteRule ^music-(.*)-([0-9_]+)\.html$ /artiste.php?g=$1&page=$2 [NC,L]
Please try this.
Upvotes: 0