简体   繁体   中英

How to remove get parameter from url with .htaccess?

My .htaccess file changes (for example) example.com/brands/beams/... to example.com/php/mvc.php?htTargUrl=brands/beams/... with QSA rule.

Here's the rule:

RewriteRule ^(.+)$ php/mvc.php?htTargUrl=$1 [QSA,L,B,BNP,NC]

And I need to remove htTargUrl parameter from original URL. For example: example.com/brands/beams/?htTargUrl=beams&par2=val to example.com/brands/beams/?par2=val .

I've tried many rules to do this, but none worked with the query string. If I use

RewriteCond %{QUERY_STRING} ^(.*)&?htTargUrl=[^&]+&?(.*)$ [NC]
RewriteRule ^/?(.*)$ /$1?%1%2 [R=301,L]

then the parameter removes not only from the original link and URL becomes example.com/php/mvc.php .

How can I do this?

RewriteCond %{QUERY_STRING} ^(.*)&?htTargUrl=[^&]+&?(.*)$ [NC] RewriteRule ^/?(.*)$ /$1?%1%2 [R=301,L]

By itself, the rule you posted should already do what you require and remove the htTargUrl=<something> URL parameter from the requested URL.

However, you need to avoid removing the URL parameter from the rewritten URL - which is what appears to be happening here. You can do this with an additional condition to target direct requests only, not rewritten requests.

For example:

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^(.*)&?htTargUrl=[^&]+&?(.*)$ [NC]
RewriteRule ^/?(.*)$ /$1?%1%2 [R=301,L]

This rule also needs to go near the top of your .htaccess file, before an existing rewrites.

By checking against the REDIRECT_STATUS environment variable we ensure that only direct requests are redirected. REDIRECT_STATUS is empty on the initial request and set to "200" (as in 200 OK HTTP response code) after the first successful rewrite.

You will need to make sure that your browser cache is cleared, since any erroneous 301 (permanent) redirects will have been cached by the browser. (For this reason it is advisable to first test with 302 - temporary - redirects.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM