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


Combine .htaccess rules: remove extension and rewrite URL variables

我有一个.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]

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

我无法弄清楚出了什么问题,代码基于此(如何?虚 URL 并忽略 .带有 .htaccess 的 PHP 扩展名 (

我的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]标志,但相同的错误仍然存在。

错误

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

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

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

%{REQUEST_FILENAME}包含我的情况下要document_root/user的文件路径。您测试document_root/user.php是否是一个文件(确实如此(,但随后.php添加到 url,这将导致/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=qwerlink.url/test重写为 test.php?q=

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

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

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

与往常一样,请参阅文档。要正确调试.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]