301使用htaccess重定向

时间:2017-04-22 13:58:29

标签: .htaccess redirect

我正在尝试在我的网站上实现一些简单的301重定向,但它们无法正常工作 - 没有错误消息或内部服务器错误。我在之前的论坛帖子上尝试了一些不同的建议但没有任何效果。以下是我的htaccess文件的完整代码:

ErrorDocument 404 http://website.com/

RewriteEngine on

Redirect 301 /recipe?recipe=1 http://website.com/recipe/recipe-a
Redirect 301 /recipe?recipe=2 http://website.com/recipe/recipe-b
Redirect 301 /recipe?recipe=3 http://website.com/recipe/recipe-c
Redirect 301 /recipe?recipe=4 http://website.com/recipe/recipe-d
Redirect 301 /recipe?recipe=5 http://website.com/recipe/recipe-e
Redirect 301 /recipe?recipe=6 http://website.com/recipe/recipe-f

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^recipe/([\w-]+)/?$ recipe.php?recipe=$1 [QSA,L]

#Remove .php extension:
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

#Force non-www:
RewriteCond %{HTTP_HOST} www.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您无法使用RewriteRule匹配查询字符串。请使用RewriteCond

Options -MultiViews
ErrorDocument 404 / 
RewriteEngine on

#Force non-www:
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L,NE]

RewriteCond %{QUERY_STRING} ^recipe=1$ [NC]
RewriteRule ^recipe(\.php)?$ /recipe/receipe-a? [L,NC,R=301]

RewriteCond %{QUERY_STRING} ^recipe=2$ [NC]
RewriteRule ^recipe(\.php)?$ /recipe/receipe-b? [L,NC,R=301]

RewriteCond %{QUERY_STRING} ^recipe=3$ [NC]
RewriteRule ^recipe(\.php)?$ /recipe/receipe-c? [L,NC,R=301]

RewriteCond %{QUERY_STRING} ^recipe=4$ [NC]
RewriteRule ^recipe(\.php)?$ /recipe/receipe-d? [L,NC,R=301]

RewriteCond %{QUERY_STRING} ^recipe=5$ [NC]
RewriteRule ^recipe(\.php)?$ /recipe/receipe-e? [L,NC,R=301]

RewriteCond %{QUERY_STRING} ^recipe=6$ [NC]
RewriteRule ^recipe(\.php)?$ /recipe/receipe-f? [L,NC,R=301]

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^recipe/([\w-]+)/?$ recipe.php?recipe=$1 [QSA,L]

#Remove .php extension:
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]