为什么我的.htaccess 301重定向规则不起作用?

问题描述:

我在我重新设计的网站上使用URL重写来给我的页面整理网址。为什么我的.htaccess 301重定向规则不起作用?

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个永久重定向,以便旧网站(重新设计之前)的页面可以重定向到新网站上的页面(用于搜索引擎优化和链接原因)。例如,页面已被重新组织,因此多个旧页面将重定向到新页面。

旧网站没有使用URL重写。因此,我想为/ about创建永久重定向,例如/about-page.php,每个旧页面使用一个规则手动执行重定向。

我已经试过几件事,比如...

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] 

DirectoryIndex index.php # -- this sets index.php to be default file for a folder 

RewriteEngine On 

# -- RewriteRule ^(.+\.php|(.+/)?index)$ - [R=404,L] 
# -- dude this above line redirects all php files to 404 error 
# -- so delete this, its a problem not solution 

RewriteCond %{SCRIPT_FILENAME}.php -f 
RewriteRule ^(.+)$ $1.php [L] 

RewriteRule ^about-page.php$ /about [R=301,L] 

这应该工作,如果发生

+0

感谢您的答复的问题发表评论。不幸的是,这似乎并不奏效。这使得“http://www.mywebsite.com/about-page.php”重定向到“http://www.mywebsite.com/home/mysite/mywebsite.com/about”,这会导致404错误。将PHP文件重定向到404错误的规则旨在通过强制用户访问重写URL(不带.php扩展名)的页面来防止在不同URL处出现重复内容。我不希望他们直接访问真正的.php文件。我认为如果在301重定向发生时可以忽略该规则,那么它会正常工作? –

+0

好的,我成功了。我遇到了很多麻烦,因为我的浏览器似乎在缓存301重定向,即使从.htaccess文件中删除规则,也会继续重定向!我似乎也需要ENV:REDIRECT_STATUS RewriteCond行,虽然我不确定它的用途。我将编辑我的问题以包含最终结果。谢谢您的帮助。 –

+1

'RewriteRule^about-page.php $/about [R = 301,L]'领先/防止重定向mywebsite.com/home/mysite/mywebsite.com/about –