【发布时间】:2011-11-08 04:23:04
【问题描述】:
我在重新设计的网站上使用 URL 重写来使我的页面更整洁。
RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^$ index.php [L]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^.+/$ %{REQUEST_URI}index.php [L]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.+\.php|(.+/)?index)$ - [R=404,L]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{SCRIPT_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [L]
这个 .htaccess 文件允许 /filename 实际上指向 /filename.php。一切正常。
但是,我现在意识到我应该设置 301 永久重定向,以便旧网站的页面(重新设计之前)可以重定向到新网站上的页面(出于 SEO 和链接原因)。页面已重新组织,例如,多个旧页面将重定向到新页面。
旧网站没有使用 URL 重写。因此,我想创建永久重定向,例如 /about-page.php 到 /about,每个旧页面使用一条规则手动执行。
我已经尝试了几件事,例如...
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^about-page.php$ about [R=301,L]
...或...
Redirect 301 /about-page.php /about
...但它总是最终要么根本不工作(当我尝试访问 /old-filename.php 时给我一个 404 错误,或者用内部服务器错误破坏一切。如果我使用它似乎工作正常Redirect 301 /about-page.html /about,但不幸的是旧 URL 使用 .php 扩展名,而不是 .html 扩展名。
我认为问题与其他规则之一有关,它将 /xyz 的请求重定向到 /xyz.php,可能会创建一些无限循环。但我不知道如何解决它。
有什么建议吗?非常感谢。
编辑:最终的工作 .htaccess 文件:
DirectoryIndex index.php #
RewriteEngine On
# -- Use a permanent redirect to point the old page to the new page.
# -- The RewriteCond is needed, or a redirect loop happens in certain cases.
# -- The full URL seems to be needed, or it redirects incorrectly.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^about-page.php$ http://www.mywebsite.com/about [R=301,L]
# -- Redirect most other .php files to a 404 error, to avoid duplicate content.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.+\.php|(.+/)?index)$ - [R=404,L]
# -- Redirect requests without an extension, but for a valid file, to that file.
# -- I'm not sure what the RewriteCond lines are for, but they both seem necessary.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{SCRIPT_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [L]
【问题讨论】:
标签: .htaccess redirect http-status-code-301