如何使用htaccess将URL的特定部分重定向到新URL?

时间:2014-06-06 13:11:12

标签: regex apache .htaccess mod-rewrite

在构建新网站时,我需要重新构建一些链接,我需要将旧链接重定向到新链接。我只有几个,如下:

about|what-we-do => about-us
contact => get-in-touch
our-work|projects => featured-work

我希望能够保留他们在这些链接后放置的任何内容。例如,我希望重定向是这样的:

our-work/web/project-title => featured-work/web/project-title

这就是我此时在htaccess文件中所拥有的内容,但这不起作用。

RewriteRule ^(about|what-we-do)(/)?  /about-us/$1      [QSA,NC,L,R=301]
RewriteRule ^contact(/)?             /get-in-touch/$1  [QSA,NC,L,R=301]
RewriteRule ^(our-work|projects)(/)? /featured-work/$1 [QSA,NC,L,R=301]

RewriteRule ^about-us(/)?$           /pg.about.php     [QSA,NC,L]
RewriteRule ^get-in-touch(/)?$       /pg.contact.php   [QSA,NC,L]
RewriteRule ^featured-work(/)?$      /pg.projects.php  [QSA,NC,L]
RewriteRule ^hello(/)?$              /pg.hello.php     [QSA,NC,L]

如果我尝试访问/about之类的内容,那么我会重定向到/about-us/about/。我并不精通htaccess。所以,如果有人能够帮助我,我将不胜感激。我会继续关注它。提前谢谢!

1 个答案:

答案 0 :(得分:2)

首次删减后,您的规则不会捕获URI部分。您可以使用:

RewriteEngine On

RewriteRule ^(?:about|what-we-do)(/.*)?$  /about-us$1 [NC,L,R=301]
RewriteRule ^contact(/.*)?$               /get-in-touch$1 [NC,L,R=301]
RewriteRule ^(?:our-work|projects)(/.*)?$ /featured-work$1 [NC,L,R=301]

RewriteRule ^about-us/?$           /pg.about.php     [NC,L]
RewriteRule ^get-in-touch/?$       /pg.contact.php   [NC,L]
RewriteRule ^featured-work/?$      /pg.projects.php  [NC,L]
RewriteRule ^hello/?$              /pg.hello.php     [NC,L]