English 中文(简体)
干净的URL重定向循环
原标题:
  • 时间:2009-01-31 16:06:00
  •  标签:

I m trying to create clean URLs on my website. Now I succeeded in configuring apache so every request like mysite.com/page will work. But I also want that requests for mysite.com/page.php will be redirected to mysite.com/page. I ve set environment variable in .htaccess to check if i already been redirected to prevent loops, but i still get them... Here s the .htaccess:

<IfModule mod_rewrite.c>
Options +FollowSymlinks

RewriteEngine On
RewriteBase /

# set the variable
RewriteRule ^$ - [L]
RewriteRule ^(.*)$ $1 [E=REWROTE:0]

# this works fine
# make mysite.com/page work and set REWROTE variable to 1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L,E=REWROTE:1]

# but if i enable this, i get redirected and then stuck in a loop
# redirect mysite.com/page.php to mysite.com/page , but only if REWROTE not 1
#RewriteCond %{ENV:REWROTE} !^1$
#RewriteRule ^(.*).php$ $1 [R=301,L]

谢谢!

最佳回答

在现有的重写规则之前添加此规则,以防止重定向请求已经被重定向一次(参考资料):

RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]
问题回答

您可以检查请求行以查看最初请求的内容:

RewriteCond %{THE_REQUEST} ^[A-Z]+ (/[^ ]*).php[? ]
RewriteRule .php$ %1 [R=301,L]

哦,而RewriteCond指令的第一个参数不是一个正则表达式,而只是一个字符串。所以转义.是错误的。

你不能使用字符串结束符$的原因是什么?

RewriteRule ^/(.+).php$ /$1

将/page.php重定向到/page,但不会在/page上进行任何重定向。

从根本上说,使用设置环境变量和添加REDIRECT_STATUS检查等技术并不非常稳健。

另一种快速而简单的方法,防止在这些情况下发生循环,并且我发现是添加查询字符串,然后检查其存在于重定向中。

RewriteCond %{QUERY_STRING} !a=a
RewriteRule ^(.*).php$ %1 [NC,R=301,L]
RewriteRule ^(.*)$ $1.php?a=a [NC,L]

在此网站上找到:http://answers.oreilly.com/topic/542-how-to-properly-redirect-for-maximum-seo/





相关问题
热门标签