Home > database >  How to redirect path with parameters using htaccess
How to redirect path with parameters using htaccess

Time:08-30

I have a series of urls that look like this:

example.com/something/page
example.com/another

that I need to redirect to

example.com/folder/to/file?q=something/page
example.com/folder/to/file?q=another

I'm not so sure where to put the %{QUERY_STRING} (or if it's needed)? Thanks in advance!

CodePudding user response:

After breaking the server numerous times, I have finally fixed this myself. I'm not sure if this is the best answer, but just a reference for anyone who might need it:

RewriteCond %{REQUEST_URI} ^/([_0-9a-z-] )$ [NC]
RewriteRule ^(.*)$ folder/to/file?q=$1 [L]

CodePudding user response:

RewriteCond %{REQUEST_URI} ^/([_0-9a-z-] )$ [NC]
RewriteRule ^(.*)$ folder/to/file?q=$1 [L]

Following on from your answer and my earlier comments... there's no need for the preceding RewriteCond directive as the necessary regex can be performed in the RewriteRule directive itself, which is also more efficient. For example, the above is equivalent to the following:

RewriteRule ^([\w-] )$ folder/to/file?q=$1 [L]

The \w shorthand character class is the same as [_0-9a-zA-Z] which also negates the need for the NC (nocase) flag.

However, this rule does not handle URLs of the form /something/page (with two path segments) as in your first example. You don't need a separate rule for this if you simply want to copy the URL-path in it's entirely to the query string (as in your example).

For example, the following would suffice:

RewriteRule ^[\w-] (/[\w-] )?$ folder/to/file?q=$0 [L]

The above matches both /another and /something/page.

Note that the $0 backreference (as opposed to $1) contains the entire URL-path that is matched by the RewriteRule pattern.

  • Related