afdggfh
afdggfh

Reputation: 135

mod_rewrite behaving strangely when . (dot) in regex

I am trying to redirect all traffic to my site to a single script as such:

example.com/fictitious/path/to/resource

should become

example.com/target.php?path=fictitious/path/to/resource

and I have set up my .htaccess file as follows:

RewriteEngine on
RewriteBase "/"
RewriteRule "^(.*)$" "target.php?path=$1"

target.php looks like this for testing purposes:

<?php echo $_GET["path"] ?>

However, when I go to "example.com/path/to/resource" target.php just echoes "target.php" instead of "path/to/resource". When I change my .htaccess as such

[...]
RewriteRule "^([a-zA-Z\/]*)$" "target.php?path=$1"

Surely enough, target.php faithfully echoes "path/to/resource", but as soon as I add an ESCAPED dot to my rule as such:

[...]
RewriteRule "^([a-zA-Z\/\.]*)$" "target.php?path=$1"

target.php echoes "target.php" again.

What is going on? Why is the dot in my regex messing with my capture group's contents in this way?

Upvotes: 1

Views: 74

Answers (1)

anubhava
anubhava

Reputation: 785541

Problem is that your rule is looping and thus running twice. After first execution REQUEST_URI becomes target.php and in 2nd execution, you get same in path parameter.

It is because you don't have any condition to avoid running this rule for existing files and directories.

You may use:

RewriteEngine on

# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ target.php?path=$1 [L,QSA]

Upvotes: 1

Related Questions