htaccess file to remove folder, and replace underscores with dashes

情到浓时终转凉″ 提交于 2020-01-06 02:55:06

问题


I need to change the following url

http://somedomain.com/news/a_sample_news_article.html

to

http://somedomain.com/post/a-sample-news-article

I have this in my htaccess which works, but I am sure it can be improved upon - does anyone have a better solution?

RewriteEngine on
# replace underscores
RewriteRule ^(news)/([^_]*)_+(.*)$ /$1/$2-$3 [L,NC,R=302]
# redirect the directory from news to post
RewriteRule ^news/(.*)$ /post/$1 [R,L]
# remove .html from end of url
RewriteRule ^(.*)\.html$ /$1 [L,R=301] 

Any help much appreciated!


回答1:


To redirect

  • /news/foo_bar

to

  • /post/foo-bar

you can use the following rule :

RewriteEngine on

# redirect "/news/foo_bar" to "/foo_bar"    
RewriteRule ^news/(.+)$ /$1 [L,R]
#2 replace underscore with hypens
RewriteRule (.*)_(.*) $1-$2 [N,E=uscores:yes]
RewriteCond %{ENV:uscores} yes
RewriteRule ^(.+)$ /post/$1 [L,R]


来源:https://stackoverflow.com/questions/37279141/htaccess-file-to-remove-folder-and-replace-underscores-with-dashes

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