0

Detecting internal redirects in url rewrite

Question

My current .htaccess file does a conditional internal redirect using quite a few RewriteRules to the contents of a sub-directory.

I am now wanting to ban all access to this sub-directory, unless they have been redirected by an internal redirect (RewriteRule).

What could I use to create this conditional statement?

Answer

Use the server variable {THE_REQUEST}, which examines the original request header sent by the browser, and is unaffected by internal rewrites (redirects are, by definition, external).

A typical request from the browser looks like this:

GET /subdir/file.ext HTTP/1.1

So, you can detect and redirect or forbid any direct access to the rewritten URL by using:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /subdir/file\.ext\ HTTP/
RewriteRule ^subdir/file\.ext$ http://www.example.com/original_fileURL [R=301,L]

-or-

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /subdir/file\.ext\ HTTP/
RewriteRule ^subdir/file\.ext$ - [F]

The redirect method is better in that it is 'friendlier' to the user, and can also be used to update any search results that now include the subdirectory URL. These rules work for all HTTP methods, such as GET, HEAD, PUT, PROPFIND, etc. as matched by the "[A=Z]{3,9}" pattern.

by 1.1K

Remember to vote! Voting helps everyone find the best posts

Tags: None