M
M
miadiva2021-08-30 19:56:28
htaccess
miadiva, 2021-08-30 19:56:28

How to make a 301 redirect from a Url with get parameters to a url without parameters but containing the values ​​from them?

Please help me understand the syntax for a 301 redirect.

You need a url with get parameters:

https://loc.mysite.com/Orders/Order?id=000001&userid=22222222222


redirected to page with url
https://loc.mysite.com/Orders/Order_id_000001_userid_22222222222


Is it possible to do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Zolin, 2021-08-30
@artzolin

You can get GET request parameters like this:

if ( isset( $_GET['id'] ) ) {
  $id = $_GET['id'];
}

It's safer to use the function for thisget_query_var()
if ( get_query_var( 'id' ) ) {
  $id = get_query_var( 'id' );
}

For this code to work you need to register available options
add_filter( 'query_vars', 'add_my_var' );
function add_my_var( $public_query_vars ) {
  $public_query_vars[] = 'id';
  return $public_query_vars;
}

All redirects must be done on the hook template_redirectusing the wp_redirect()or function wp_safe_redirect(). You parse the link, check the necessary redirect conditions, and build a new link. Here is the template:
add_action( 'template_redirect', 'custom_template_redirect' );
function custom_template_redirect() {

  if ( $condition ) {
    wp_redirect( home_url( '/' ) );
    exit();
  }

}

V
Viktor Taran, 2021-08-31
@shambler81

The GET parameter is not part of the url and does not fall into the RewriteRule, so you can only work with it through %{QUERY_STRING}
RewriteCond - this is if they add up to the RewriteRule

RewriteCond %{QUERY_STRING} (?:^|&)id\=000001(?:$|&)
RewriteCond %{QUERY_STRING} (?:^|&)userid\=22222222222(?:$|&)
RewriteRule ^Orders/Order$ /Orders/Order_id_000001_userid_22222222222? [L,R=301]

Suitable for all variants
RewriteCond %{QUERY_STRING} (?:^|&)id\=(.+)(?:$|&)
RewriteCond %{QUERY_STRING} (?:^|&)userid\=(.+)(?:$|&)
RewriteRule ^Orders/Order$ /Orders/Order_id_%1_userid_%2? [L,R=301]

where %1is a group from RewriteCond , %2respectively
(?:- this sign animates this group so that it does not interfere

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question