Why would mod_rewrite rewrite twice?

一世执手 提交于 2019-12-11 13:41:46

问题


I only recently found out about URL rewriting, so I've still got a lot to learn.

While following the Easy Mod Rewrite tutorial, the results of one of their examples is really confusing me.

RewriteBase /
RewriteRule (.*) index.php?page=$1 [QSA,L]

Rewrites /home as /index.php?page=index.php&page=home.

I thought the duplicates might have had been caused by something in my host's configs, but a clean install of XAMPP does the same.

So, does anyone know why this seems to parse twice?

And, to me this seems like, if it's going to do this, it would be an infinite loop -- why does it stop at 2 cycles?


回答1:


From Example 1 on this page, which is part of the tutorial linked in your question:

Assume you are using a CMS system that rewrites requests for everything to a single index.php script.

RewriteRule ^(.*)$ index.php?PAGE=$1 [L,QSA]

Yet every time you run that, regardless of which file you request, the PAGE variable always contains "index.php".

Why? You will end up doing two rewrites. Firstly, you request test.php. This gets rewritten to index.php?PAGE=test.php. A second request is now made for index.php?PAGE=test.php. This still matches your rewrite pattern, and in turn gets rewritten to index.php?PAGE=index.php.

One solution would be to add a RewriteCond that checks if the file is already "index.php". A better solution that also allows you to keep images and CSS files in the same directory is to use a RewriteCond that checks if the file exists, using -f.


1the link is to the Internet Archive, since the tutorial website appears to be offline




回答2:


From the Apache Module mod_rewrite documentation:

'last|L' (last rule)
[…] if the RewriteRule generates an internal redirect […] this will reinject the request and will cause processing to be repeated starting from the first RewriteRule.

To prevent this you could either use an additional RewriteCond directive:

RewriteCond %{REQUEST_URI} !^/index\.php$
RewriteRule (.*) index.php?page=$1 [QSA,L]

Or you alter the pattern to not match index.php and use the REQUEST_URI variable, either in the redirect or later in PHP ($_SERVER['REQUEST_URI']).

RewriteRule !^index\.php$ index.php?page=%{REQUEST_URI} [QSA,L]


来源:https://stackoverflow.com/questions/499970/why-would-mod-rewrite-rewrite-twice

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