Apache Rewrite rule to replace underscore with hyphen and append extension at end

徘徊边缘 提交于 2019-12-12 00:57:43

问题


I need help to create apache rewrite rule. My requirement is as given below.

Source URL: "http://localhost/directory/file_name_1"

Destination URL: "http://localhost/file-name-1.html"

Note: Above requirement is not for static URL, but there would be any other word instead of "directory" and "file_name_1".

  • "directory" word should be removed in new redirected URL
  • underscore ( _ ) should be replaced with Hyphen ( - )
  • "file-name-1" should be ended with .html extension.

I appreciate your reply.


回答1:


Try this one

RewriteEngine On
RewriteRule ^(/?.*/[^/]*?)_([^/]*?_[^/]*)$ $1-$2 [N]
RewriteRule ^(/?.*/[^/]*?)_([^/_]*)$ $1-$2 [R=301]



回答2:


I have used below rules and now it is working.

    RewriteEngine    On
    RewriteCond     %{REQUEST_URI}  !^/([A-Za-z0-9]+)/([A-Za-z0-9_]+)$
    RewriteRule     .*    - [S=3]
    RewriteRule     ^(/?.*/[^/]*?)_([^/]*?_[^/]*)$ $1-$2 [N]
    RewriteRule     ^(/?.*/[^/]*?)_([^/_]*)$ $1-$2.html  [NC]
    RewriteRule     ^/(.*)/(.*)$        $2               [R,L]


来源:https://stackoverflow.com/questions/13190407/apache-rewrite-rule-to-replace-underscore-with-hyphen-and-append-extension-at-en

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!