Preserve query string in htaccess

Viewed 55

I have the following .htaccess rules:

    RewriteEngine On
    RewriteBase /
    RewriteCond %{QUERY_STRING} page=(.*)
    RewriteRule ^(.)([^/])([^/])[^/]*/$ /htcache/videos/$1/$2/$3/$0%{QUERY_STRING}.html? [L]
    RewriteRule ^$ /htcache/index.html [L]
    RewriteRule ^(.)([^/])([^/])[^/]*\.html$ /htcache/video/$1/$2/$3/$0 [L]
    RewriteRule ^(.)([^/])([^/])[^/]*\/$ /htcache/videos/$1/$2/$3/$0\index.html [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

in this rules if a requested url contain a query string and file is not exist in htcache folder the rewrite rule work but the query string is not executed

request eg https://www.mywebsite.com/fun-videos/?page=2 if file exist /htcache/videos/f/u/n/fun-videos/page=2.html "file found"

But if file is not present the page /index.php is executed without the query string.

some ideas???

1 Answers
RewriteCond %{QUERY_STRING} page=(.*)
RewriteRule ^(.)([^/])([^/])[^/]*/$ /htcache/videos/$1/$2/$3/$0%{QUERY_STRING}.html? [L]

The problem here is that you are rewriting to the "cache file" (and removing the query string with the trailing ?) regardless of whether the cache file exists or not.

It is only when the "cache file" does not exist are you rewriting the already rewritten request (without a query string) to index.php.

You should first check that the cached file exists before rewriting to it. Although simply removing the trailing ? on the first rule will prevent the query string from being removed.

Note also that the condition is simply checking whether page= is present anywhere in the query string, not strictly that there is a page URL parameter - if that matters.

RewriteRule ^(.)([^/])([^/])[^/]*\/$ /htcache/videos/$1/$2/$3/$0\index.html [L]

Aside: There is no need to backslash-escape the last slash in the TestString (first argument) and \i in the substitution string is just a literal i - unless that should really be /i?

For example, try it like this instead:

RewriteEngine On

RewriteCond %{QUERY_STRING} page=
RewriteCond %{DOCUMENT_ROOT}/htcache/videos/$1/$2/$3/$0%{QUERY_STRING}\.html -f
RewriteRule ^(.)([^/])([^/])[^/]*/$ /htcache/videos/$1/$2/$3/$0%{QUERY_STRING}.html? [L]

RewriteRule ^$ /htcache/index.html [L]

RewriteCond %{DOCUMENT_ROOT}/htcache/video/$1/$2/$3/$0 -f
RewriteRule ^(.)([^/])([^/])[^/]*\.html$ /htcache/video/$1/$2/$3/$0 [L]

RewriteCond %{DOCUMENT_ROOT}/htcache/videos/$1/$2/$3/$0index.html -f
RewriteRule ^(.)([^/])([^/])[^/]*/$ /htcache/videos/$1/$2/$3/$0index.html [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

You are not actually using the RewriteBase directive here, so I removed it.

Related