One possible reason for this issue is that the rewrite rules you have added do not account for the prefix in the URL. To fix this, you need to modify your rewrite rule pattern to include the prefix. Here’s an updated version of the code snippet you provided:
function my_add_rewrite_rules( $rules ) {
$new_rules = array();
// ... existing rules here
$new_rules['^([a-z]{2})/([a-z]+)/?$'] = 'index.php?name=$matches[2]&cscountry=$matches[1]';
// Updated pattern: ^([a-z]{2}) - matches the 2-char prefix
// /([a-z]+) - matches the page name
// ... more rules
$new_rules = $new_rules + $rules;
return $new_rules;
}
add_action('rewrite_rules_array', 'my_add_rewrite_rules');
With this modification, the rewrite rules should correctly handle URLs with the prefix. For example, https://site.com/aa/?s=term will be rewritten to index.php?name=term&cscountry=aa, and the appropriate page should be displayed instead of a 404 error.
Please note that you may need to flush the rewrite rules for the changes to take effect. You can do this by visiting the “Permalinks” settings page in your WordPress admin dashboard and simply saving the settings again.
Thread Starter
MrAnt
(@mant)
Hi Albert,
Thanks for the response. It looks like you have replaced my (.*) with ([a-z]+) which are very similar. The + would be 1 or more characters, compared to the asterisk I used which is 0 or more. The . in my case included any characters apart from line breaks, whereas [a-z] limits to lower case letters.
I was trying to address urls like https://caloriestar.com/gb/?s=chocolate so the [a-z]+ would not match as there is only the trailing slash before the query parameters.
In the end as the rewrite rules were working fine apart from the search I used the nginx rewrite functionality to resolve.
location ~ "/(?<cn>[a-z]{2})/?$" {
if ($arg_s != "") {
return 301 /$cn/search/$arg_s;
}
try_files $cn/$uri /index.php?$args&countrycn=$cn;
}
Although I used the following code to change the Search URL, this did not seem to be picked up everywhere, so I write a shortcode that would output the correct code based on country selected.
function change_search_url_rewrite() {
if ( is_search() && ! empty( $_GET['s'] ) ) {
$country = get_query_var('cscountry');
if ($country <> '') {
$country = '/'.$country;
}
wp_redirect( home_url( $country."/search/" ) . urlencode( get_query_var( 's' ) ) );
exit();
}
}
add_action( 'template_redirect', 'change_search_url_rewrite' );
Putting this here in case it comes in useful to others in the future.
-
This reply was modified 2 years, 11 months ago by
MrAnt. Reason: Edited to mark as resolved