Default Query String in .htaccess

2019-08-09 02:12发布

问题:

Bit of an odd question, but I'd like to have a query string set on all of my URLs. If the parameter isn't set (or is empty), then I'd like to redirect to include a default.

For example:

example.com would need to requrect to example.com?param=a

example.com?param would also need to redirect to example.com?param=a

If the param is set and is part of a list of known values, then it should carry on as normal:

example.com?param=(a|b|c|d) would go to the respective page a,b,c or d

Some pages of the site use other parameters to sort and paginate, so the rules cannot assume that this is the only query string.

I've tried a couple of things, but kept getting stuck in a redirect loop. This is trying to set the default param:

RewriteCond %{QUERY_STRING} !(^|&)param=(a|b|c|d)($|&)
RewriteRule ^(.*)$ /index.php?rq=$1&param=a [L,QSA]

The main CMS rewrite rule is:

RewriteCond %{REQUEST_URI} !^\/*(index\.php|blog|admin\/assets|site\/assets|robots.txt|sitemap(|\-[0-9]+)\.xml|products.xml|favicon\.ico)
RewriteRule ^(.*)$ /index.php?rq=$1 [L,QSA]

Any help would be great!

回答1:

RewriteCond %{QUERY_STRING} !(^|&)param=(a|b|c|d)($|&)
RewriteCond %{REQUEST_URI} !^\/*(index\.php|blog|admin\/assets|site\/assets|robots.txt|sitemap(|\-[0-9]+)\.xml|products.xml|favicon\.ico)
RewriteRule ^(.*)$ $1?%{QUERY_STRING}&param=a [L]

RewriteCond %{REQUEST_URI} !^\/*(index\.php|blog|admin\/assets|site\/assets|robots.txt|sitemap(|\-[0-9]+)\.xml|products.xml|favicon\.ico)
RewriteRule ^(.*)$ /index.php?rq=$1 [L,QSA]