.htaccess规则,将旧的不存在地址重定向到新地址

时间:2013-02-22 21:06:18

标签: apache .htaccess mod-rewrite

以下是如何在博客上查看我的旧帖子:

subdomain.domain.com/view/1310/article-title/

我希望当访问者来自谷歌这样的地址时,可以像这样重定向:

http://www.domain.com/article-title/

我需要指定一些关于旧/第一个链接的详细信息:

  • 子域,是一个变量
  • 查看,是一个固定的词
  • 1230 ,可以是任意数字/身份

我试过了:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} subdomain.domain.com $ [NC]
RewriteRule ^/view/(*)/(.*)$ http://www.domain.com/$2 [R=301,L]

导致500大错误。

网站正在对WordPress cms做出裁决。

提前致谢!


在Michael Berkowski的回答之后添加。我目前的wp规则是:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

1 个答案:

答案 0 :(得分:3)

500错误是(*)的结果,其中*(零或更多)之前没有任何内容作为限定符。您可能打算(.*),但您需要[^/]+才能让所有角色到达下一个/

Options +FollowSymLinks
RewriteEngine On
# Slight modification of the subdomain - must escape .
RewriteCond %{HTTP_HOST} subdomain\.domain\.com$ [NC]
# Note this may need to be ^view/ instead of ^/view
# In htaccess context the leading / should probably not be there
RewriteRule ^/view/([^/]+)/(.*)$ http://www.domain.com/$2 [R=301,L]

以上内容专门针对subdomain.domain.com,但由于您指定它是变量,因此使用此选项可获取除www.domain.com以外的所有子域:

Options +FollowSymLinks
RewriteEngine On
# Matches all subdomains except www.
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^/view/([^/]+)/(.*)$ http://www.domain.com/$2 [R=301,L]

如果没有这个,请发布您可能拥有的任何其他重写规则(因为您提到这是WordPress,我希望您有其他规则)因为订单可能很重要。

更新包含WordPress规则:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# The new rules handle the subdomain redirect...
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^view/([^/]+)/(.*)$ http://www.domain.com/$2 [R=301,L]

# After which WordPress does its internal redirection
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
相关问题