Append query string to all URLs with .htaccess

2019-08-08 17:39发布

问题:

For testing purposes, I would like to append a query string (let's say testing=true) to any url requested from my website.

E.g. I want to change

  • example.com
  • example.com/product
  • example.com/search?q=string

to

  • example.com?testing=true
  • example.com/product?testing=true
  • example.com/search?q=string&testing=true

I tried this:

RewriteRule ^/?(.*) http://example.com/$1?testing=true [L,R,NE]

but it breaks the site. Not an expert.

Any ideas?

EDIT:

I should add I'm working with CodeIgniter (PHP) and my current .htaccess looks like this:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteCond $1 !^(index\.php|public|images|robots\.txt|css)
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

回答1:

You can use this new rule:

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{QUERY_STRING} !(^|&)testing=true(&|$) [NC]
    RewriteRule ^ %{REQUEST_URI}?testing=true [L,QSA,R]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond $1 !^(index\.php|public|images|robots\.txt|css)
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>