简体   繁体   English

url从_重定向到-htaccess

[英]url redirect from _ to - htaccess

I have problem in my URL.我的网址有问题。

This is my code in htaccess:这是我在 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.因此,Google 或 Bing 上的某些 URL 可能会像这样显示music_(.*)_([0-9_]+)\\.html如果可能,我想使用 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 - .我希望任何带有_ url 更改为- ,因为所有链接都可以正确使用-但在我的研究中,一些 URL 具有_所以我想用-替换它们。 example:例子:

Error : http://www.example.com/me_like_this.html Correct : http://www.example.com/me-like-this.html错误: http : //www.example.com/me_like_this.html正确: http : //www.example.com/me-like-this.html

You can use the following in your /.htaccess file:您可以在/.htaccess文件中使用以下内容:

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 .如果这对您有用,并且您想让浏览器和搜索引擎缓存重定向,请将302更改为301

Note: In your RewriteRule I have changed .* to .+ so it only matches one or more characters, instead of zero or more characters.注意:在您的RewriteRule我已将.*更改为.+因此它仅匹配一个或多个字符,而不是零个或多个字符。 Additionally, I have changed [0-9_]+ to \\d+ , which is the shorthand equivalent without including underscores, which would be converted to hyphens anyway.此外,我已将[0-9_]+更改为\\d+ ,这是不包括下划线的速记等效项,无论如何都会转换为连字符。 If you want to include hyphens in the last capture group, then change (\\d+) to ([\\d-]+) .如果要在最后一个捕获组中包含连字符,请将(\\d+)更改为([\\d-]+)

RewriteEngine On
RewriteRule ^(.*)_(.*)$ /$1-$2 [L,R=301]
RewriteRule ^music-(.*)-([0-9_]+)\.html$ /artiste.php?g=$1&page=$2 [NC,L]

Please try this.请试试这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM