M
M
Morozov_Evgeny2016-09-01 12:17:00
Regular Expressions
Morozov_Evgeny, 2016-09-01 12:17:00

Explain the magic: How does this RewriteRule work?

I came across a completely magical behavior of this rule in htaccess:

RewriteCond %{THE_REQUEST} //
RewriteRule ^(.*)$ /$0 [R=302,L]

What this rule does: if there are several slashes in a row in the request (after the domain name, in the middle or at the end), then we remove the duplicate slashes and leave only one slash.
This rule has magical behavior.
The content of the htaccess file
============================================= =================================
AddDefaultCharset utf-8
DirectorySlash Off
RewriteEngine On

# If the request contains several slashes in a row (after the domain name, in the middle or at the end), then remove the double slashes and leave only one slash
RewriteCond %{THE_REQUEST} //
RewriteRule ^(.*)$ /$0 [R=302,L]

# If the request matches a directory (for example, morozov.one/pages or morozov.one or morozov.one/) and there is an index.html file inside this directory, then we redirect: add /index.html to the end of the request
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME}/index.html -f
RewriteRule ^(.*)$ %{REQUEST_URI}/index.html [R=302,L]

================================================= ===============================
And here the magic begins!
Request: morozov.one/pages/
Final address: morozov.one/pages/index.html
Everything is OK! The first rule didn't work, the second did.
Let's go further.
Request: morozov.one/pages////
Final address: morozov.one/pages/index.html
Everything is OK! The first rule worked, the second worked.
Let's go further.
Request: morozov.one
Final address: morozov.one/index.html
Magic!
Logically, the final request should look like:
morozov.one//index.html (two slashes)
The first rule will not be executed, because there are no paired slashes in the original query, but the second rule will be executed.
But in practice, two slashes do not work, as if the rule %{THE_REQUEST} // works at the very end! But it's in the beginning!
Questions:
How does this (%{THE_REQUEST} //) rule work?
Can you explain step by step?
Does it work in several passes or in one?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Viktor Taran, 2016-09-01
@shambler81

everything is simple this rule removes two slashes in a row, if there are 2 of them.
If there are more than a hedgehog, then htaccess spins in a circle until it stops and all urls after passing remain unchanged (this is not a rule, but generally applies to .htaccess). So here everything works locally, there is no magic.
And if you understand that .htaccess is chasing in circles, then the magic disappears.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question