结合.htaccess规则:删除扩展并重写URL变量

时间:2013-09-27 12:14:20

标签: php .htaccess url-rewriting vanity-url

我有.htaccess个文件,其中包含以下规则

# replace 'RewriteBase' with current working folder
# put '<base href="/">' in <head> if you are in the root folder
# put '<base href="/foldername/">' in <head> if you are in a subfolder of the root
Options +FollowSymLinks
RewriteEngine On
RewriteBase /pretty-urls

# Remove slash if file
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ $1 [R=301,L]

# Redirect to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ $1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .* - [L]
RewriteRule ^(.*)$ user.php?u=$1 [NC]

这基本上会将以下任何网址www.mysite.com/about.phpwww.mysite.com/aboutwww.mysite.com/about/转换并重定向到www.mysite.com/about,并且还应该允许我编写www.mysite.com/user/john但而是抛出内部服务器错误加上500。

我无法弄清楚出了什么问题,代码基于此(How-to? Vanity URL & ignore .PHP extension with .htaccess

我的php看起来像这样

foreach ( $users as $user ) {
    echo '<p><a href="user/'.$user->username.'">'.$user->username.'</a></p>';
}

感谢任何帮助,谢谢。

编辑:Apache错误日志说

[Fri Sep 27 14:26:26.539589 2013] [core:error] [pid 2276:tid 1680] [client ::1:60023] AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace., referer: http://localhost/pretty-urls/users

根据建议,我删除了[NC]标记并添加了[L]标记,但同样的错误仍然存​​在。

1 个答案:

答案 0 :(得分:2)

错误Request exceeded the limit of 10 internal redirects通常是由重写规则引起的,该规则既匹配原始网址又匹配重写的网址。 L标志只会停止重写当前周期,但是当apache再次通过.htaccess推送请求时,这不会阻止这些错误的内部重定向。

在我自己的本地主机上重新创建时,我注意到问题是将.php添加到您的网址的规则。

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]
在我的案例中,

%{REQUEST_FILENAME}包含document_root/user的文件路径。您测试document_root/user.php是否为文件(它是),然后将.php添加到网址,这将导致/user/john/.php。我认为可以解决问题,将文件移动到子目录,以便虚拟URL永远不会与文件夹中的文件或目录匹配。

您可以将规则更改为以下内容,但我不确定这是否会完全消除此问题:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/]+)/?(.*)$ $1.php?q=$2 [L]

这会将link.url/test/qwer重写为test.php?q=qwer,将link.url/test重写为test.php?q=

您对user.php进行内部重写的规则应移至“常规”规则之上,并应更改为:

RewriteRule ^user/(.*)/?$ user.php?u=$1 [NC,L]

这会将link.url/user/john/重写为user.php?u=john

与往常一样,请参阅the documentation。要正确调试.htaccess,请将LogLevel alert rewrite:trace3放入httpd.conf并重新启动该服务。这将显示如下所示的行,它们可以让您了解正在发生的事情:

[rewrite:trace1] [pid 4800:tid 1532] mod_rewrite.c(468): [client ::1:49451] ::1 - - [localhost/sid#3ecb48][rid#12b1a88/initial/redir#2] [perdir C:/wamp/www/] internal redirect with /user/john/.php.php.php [INTERNAL REDIRECT]