使用mod_rewrite删除.php扩展名并同时清除GET URL

时间:2013-11-07 23:32:51

标签: php regex apache .htaccess mod-rewrite

这是我迄今为止所尝试过的:

RewriteEngine On

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

RewriteCond %{QUERY_STRING} ^id=([0-9]{1})$
RewriteRule ^article\.php$ /article/%1 [L]

基本上,第一组规则将URL从something.php转换为某些内容。

第二套规则应该将其中包含article.php?id = NUM​​BER的任何内容替换为/ article / NUMBER。

Apache报道:

AH00124: Request exceeded the limit of 10 internal redirects due to probable 
configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary.

2 个答案:

答案 0 :(得分:2)

The second set of rules is supposed to replace anything that has article.php?id=NUMBER in it into /article/NUMBER.

我相信你的规则已经逆转。

请尝试使用此代码:

RewriteEngine On
RewriteBase /mellori/

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} /article\.php\?id=([^\s&]+) [NC]
RewriteRule ^ article/%1? [R=302,L]

# internally rewrites /article/123 to article.php?id=123
RewriteRule ^article/([0-9]+)$ article.php?id=$1 [L,NC,QSA]

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

答案 1 :(得分:0)

您需要确保何时匹配^article\.php$它来自实际请求而不是之前规则重写的URI。因此,您可以为内部重定向附加ENV检查,或者与'%{THE_REQUEST}匹配。

您的选择:

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^id=([0-9]{1})$
RewriteRule ^article\.php$ /article/%1 [L]

RewriteCond %{THE_REQUEST} \ /+article\.php\?id=([0-9]{1})(\ |$)
RewriteRule ^ /article/%1 [L]