How to use mod rewrite %{THE_REQUEST} variable in htaccess?

Many users who use htaccess often get confused by mod-rewrite %{THE_REQUEST} variable. The questions what is it and how do we use it appear on their mind. In this post I will explain what %{THE_REQUEST} actually is and how we can use it in rewriteRule.

What is %{THE_REQUEST} in mod rewrite?

%{THE_REQUEST} is a mod rewrite per defined variable like other variable ie %{HTTP_HOST} . To understand what URI string the_request variable actually contains you can write a rule to print it.
THE_REQUEST variable contains the full URI string including Request method and Server protocol. The following is the example of THE_REQUEST string . When you type /file.php in your browser , your browser sends the following request to server:

GET /file.php HTTP/1.1

  • GET is the request method
  • /file.php is the file you requested.
  • HTTP/1.1 is the protocol version of your apache server.

We use %{THE_REQUEST} in RewriteCond to conditionally rewrite urls and avoid infinite loop error as this variable works as an anti loop protection for rewriteRules.

RewriteEngine On
RewriteCond %{THE_REQUEST} GETs/file.phpsHTTP1.1 [NC]
RewriteRule (.*) /file [R]

In the example above we match against %{THE_REQUEST} using regex. If the regex pattern matches then the rule is triggered. The rule will redirect /file.php to /file. You can also use a simple regex pattern that only matches the file name

RewriteEngine On
RewriteCond %{THE_REQUEST} file.php [NC]
RewriteRule (.*) /file [R]

THE_REQUEST variable is often used with rules that remove file extensions. When two rules (Rule with R flag and Rule with L) rewrite the same file name THE_THE_REQUEST should be used at the top of External rewrite rule (Rule with R flag) to avoid the loop error.

Leave a Reply

Your email address will not be published. Required fields are marked *