Search code examples
regexapache.htaccessmod-rewritepcre

RewriteRule not capturing backreference


I have a RewriteRule in an .htaccess file but am not able to make it work correctly:

RewriteRule ^(?!(redirect-build)) redirect-build/index.php?url=$1

The backreference $1 isn't captured and Apache rewrites the URL parameter with no value in it. Here is a snippet of the log file:

[Fri Mar 13 13:46:26.254929 2020] [rewrite:trace2] [pid 10612:tid 1344] mod_rewrite.c(477): [client 127.0.0.1:58838] 127.0.0.1 - - [domain/sid#1c4a1bda5b0][rid#1c4a2df8180/initial] [perdir D:/document-root/path/to/directory/] rewrite 'zalety-jablek' -> 'redirect-build/index.php?url='
[Fri Mar 13 13:46:26.254929 2020] [rewrite:trace3] [pid 10612:tid 1344] mod_rewrite.c(477): [client 127.0.0.1:58838] 127.0.0.1 - - [domain/sid#1c4a1bda5b0][rid#1c4a2df8180/initial] split uri=redirect-build/index.php?url= -> uri=redirect-build/index.php, args=url=

Is there any solution to it?


Solution

  • Example: example.com/some-path should resolve to: example.com/redirect-build/index.php?url=some-path

    In that case you need to adjust your RewriteRule pattern to allow it to match & capture value like this:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([\w-]+)/?$ redirect-build/index.php?url=$1 [L,QSA,NC]
    
    • ([\w-]+) is capture group to match and capture 1+ of any word character or a hyphen
    • RewriteCond is used to skip existing files and directories from this rewrite