Home > OS >  Redirecting query string for any search query for all URLs
Redirecting query string for any search query for all URLs

Time:01-07

I want to ask if it is possible to redirect

example.com/something?query=hell

to

example.com/something/hell

with the help of htaccess. I want to do it for all query i pass with GET method. Does anyone has any idea??

CodePudding user response:

You can do this with the following rule in your htaccess

RewriteEngine On


RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/] )/?$ /something?query=$1 [L]

With the rule above you can just type example.com/foobar into your browser to access the page at example.com/something?query=foobar .

CodePudding user response:

To "redirect" /something?query=hell to /something/hell you would do it like the following using mod_rewrite:

RewriteEngine On

RewriteCond %{QUERY_STRING} ^query=([^&]*)
RewriteRule ^something$ /$0/%1 [QSD,R=302,L]

The RewriteRule pattern matches against the URL-path only. You need an additional condition that matches against the QUERY_STRING server variable in order to match the query string.

The $0 backreference contains "something" from the URL-path and %1 contains the value of the query URL parameter, eg. "hell", (captured in the preceding CondPattern).

Note that the query URL param must occur at the start of the query string, as in your example.

The QSD flag is required to discard the query string.

However, if you are later rewriting the URL back to the query string (implementing "pretty" URLs) then you will need an additional condition to prevent a redirect loop (to prevent the rewritten request being redirected). For example:

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^query=([^&]*)
RewriteRule ^something$ /$0/%1 [QSD,R=302,L]
  •  Tags:  
  • Related