怎么样? (.htaccess重定向301)

时间:2012-06-19 13:17:35

标签: .htaccess redirect http-status-code-301

我在localhost / gallery /文件夹中有一个站点。我想这样做: - 当我写localhost / gallery / 12真正的地址时,打开的是localhost / gallery / index.php?url = 12 我试图做到但不幸的是它不起作用。返回错误310(ERR_TOO_MANY_REDIRECTS)。

AddDefaultCharset UTF-8

Options +FollowSymlinks -Indexes
RewriteEngine On
RewriteCond %{THE_REQUEST} /index\.(php|html)\ HTTP/
RewriteRule ^index\.(php|html)$ / [R=301,L]
RewriteRule ^(.*)$ http://localhost/gallery/$1 [R=301,L]

RewriteBase /

RewriteRule ^([^.]+)$ index.php?url=$1 [L,NC,QSA]

1 个答案:

答案 0 :(得分:1)

以下行实际上会强制进行EXTERNAL重定向:

RewriteRule ^(.*)$ http://localhost/gallery/$1 [R=301,L]

因此,对http://localhost/foobar的请求将导致301响应,告知客户端请求http://localhost/gallery/foobar。客户端现在http://localhost/gallery/foobar发出新请求,现在会对http://localhost/gallery/gallery/foobar产生301响应,依此类推。

请改为尝试:

AddDefaultCharset UTF-8

Options +FollowSymlinks -Indexes
RewriteEngine On
RewriteCond %{THE_REQUEST} /index\.(php|html)\ HTTP/
RewriteRule ^index\.(php|html)$ / [R=301,L]

RewriteCond %{REQUEST_URI} !^/gallery/
RewriteRule ^(.*)$ http://localhost/gallery/$1 [R=301,L]

RewriteBase /
RewriteRule ^gallery/([^.]+)/?$ gallery/index.php?url=$1 [NC,QSA,L]

请注意,我在无限循环规则之前添加了重写条件,以阻止已经以/ gallery开头的URL激活该重定向。

另外,我已经修改了文件规则,正如您所描述的那样正确地将http://localhost/gallery/foobar重写为http://localhost/gallery/index.php?url=foobar。请注意,此模式中的/?为您提供了可选的尾部斜杠,因此http://localhost/gallery/12http://localhost/gallery/12/都可以正常工作。如果您不想要后者,请从模式中删除/?