首页 > 解决方案 > 在 htaccess 中保留查询字符串

问题描述

我有以下.htaccess规则:

    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]

在此规则中,如果请求的 url 包含查询字符串并且 htcache 文件夹中不存在文件,则重写规则有效,但查询字符串未执行

请求,例如https://www.mywebsite.com/fun-videos/?page=2 ,如果文件存在/htcache/videos/f/u/n/fun-videos/page=2.html“找到文件”

但是如果文件不存在,/index.php则在没有查询字符串的情况下执行页面。

一些想法???

标签: apache.htaccessmod-rewrite

解决方案


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

这里的问题是,无论缓存文件是否存在,您都在重写“缓存文件”(并删除带有尾随的查询字符串)。?

只有当“缓存文件”不存在时,您才会将已经重写的请求(没有查询字符串)重写为index.php.

在重写之前,您应该首先检查缓存文件是否存在。尽管简单地删除?第一条规则的尾随将阻止查询字符串被删除。

另请注意,条件只是检查page=查询字符串中是否存在任何位置,而不是严格地检查是否存在pageURL 参数 - 如果这很重要。

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

旁白:不需要反斜杠转义TestString(第一个参数)\i中的最后一个斜杠,并且替换字符串只是一个文字i- 除非那真的应该是/i

例如,改为这样尝试:

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]

您实际上并没有在RewriteBase这里使用该指令,因此我将其删除。


推荐阅读