问题
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