apache.htaccessmod-rewritepcreapache2.2

Apache RewriteRule RegEx not working as intended


I want to rewrite the URLs:

/Files/ANYFILENAMEHERE?token=ANYTOKENHERE

to

/do_download.php?file=ANYFILENAMEHERE&token=ANYTOKENHERE

For this I am using the following rule in my .htaccess:

RewriteEngine On
RewriteRule ^Files\/([^\?]+)\?token=([a-z0-9]+)$ do_download.php?file=$1&token=$2 [L]

However, the URL does not get rewritten. It just returns a 404 error. On Regex101 in PCRE mode however it matches for some reason.

Why is this and how can I fix this? Am I doing a stupid mistake somewhere?

My Apache version is 2.2.31 (Unix) btw.


Solution

  • You cannot match for the query string in a rewrite rule.

    Try this instead:

    RewriteCond %{QUERY_STRING} token=([^&]+)(&|$)
    RewriteRule ^Files/(.+) /do_download.php?file=$1&token=%1
    

    Here the rewrite condition looks for the token in the query string while the rewrite rule handles the filename.

    Demo here: http://htaccess.mwl.be?share=fa3b4b46-b0c9-5406-a25b-605ca687d8bd