Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

.htaccess - htaccess file - how do these redirects work?

it's really difficult to understand htaccess's work, I have this code:

#Remove slash on the end
RewriteRule ^(.*)/$ $1 [R=301]

#Don't use .php extension in URL
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php

#All the directories should be redirected to index.php
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule . index [R=301]

Structure of my root folder: index.php, .htaccess and dir directory with test.php file inside.

I know that this file re-executes multiple times until the changes in URL are over, so if I'm writing mysite.ru/index/dir/ to address bar for example (I use existing index file as directory, otherwise, if I use words that aren't related to existing file names, it's works), I'm expecting 404 page (Slash removes, dir.php doesn't exist, index/dir doesn't exist, file executes again, URL didn't changed and it's over), but I'm getting 500 error and 10 redirects in error.log file. Something wrong with .htacess file, and I can't understang what.

question from:https://stackoverflow.com/questions/65648004/htaccess-file-how-do-these-redirects-work

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use END flag or RewriteCond %{ENV:REDIRECT_STATUS} ^$ condition to prevent the infinite rewrite loop error.

END flag works on Apache version 2.4 or greater

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [END]

The following condition works on all versions

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php

The reason why you got internal server error (Too many redirects) is because your rule rewrites the same request multiple times. Your rule gets triggered when you request /filename/blabla .
Since the /filename/blabla doesn't map to an existing file your condition RewriteCond %{REQUEST_FILENAME}.php -f only checks the first path segment /filename . the condition is met and the rule gets triggered in loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...