mod_rewrite - redirect to root and replace underscores with dashes

走远了吗. 提交于 2020-01-05 04:11:14

问题


I have been agonising over this for a few hours - trying to get to grips with the syntax for mnod_rewrite, Basically, I am migrating a site so that urls like:

http://www.somedomain.co.uk/news/article/a_blog_post

becomes

http://www.somedomain.co.uk/a-blog-post

The two key things here are removing the "/news/article" bit and replacing underscores with dashes.

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/?news/article$
RewriteRule ^([^_]*)_([^_]*_.*)$ $1-$2 [N]

RewriteCond %{REQUEST_URI} ^/news
RewriteRule ^([^_]*)_([^_]*)$ $1-$2 [N]

RewriteRule ^news/article/(.*)$ /$1 [L,R=301]

I can't seem to get the RewriteCond to fire. Please help!


回答1:


You can do it like this:

RewriteEngine On

# remove /news/article/ when there is no _ left
RewriteRule ^news/article/([^_]+)$ /$1 [L,R=301,NC,NE]

# use recursion based rule to repalce _ by -
RewriteRule ^(news/article/[^_]*)_+(.*)$ $1-$2 [N,DPI]


来源:https://stackoverflow.com/questions/40001041/mod-rewrite-redirect-to-root-and-replace-underscores-with-dashes

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