Use mod_rewrite to remove .php extension and clean GET urls concurrently

吃可爱长大的小学妹 提交于 2019-12-23 08:33:43

问题


This is what I've tried till now:

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]

Basically, the first set of rules converts the URLs from something.php to something.

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

Apache reports:

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

回答1:


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

I believe you have rules reversed.

Try this code instead:

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]



回答2:


You need to make sure when you match against ^article\.php$ that it is from the actual request and not the URI that's been rewritten by the previous rule. So you can either append an ENV check for an internal redirect, or match against `%{THE_REQUEST}.

Your choice:

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

or

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


来源:https://stackoverflow.com/questions/19848872/use-mod-rewrite-to-remove-php-extension-and-clean-get-urls-concurrently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!