RewriteRule accepts numbers but not letters in tag
-
15-01-2021 - |
Question
RewriteRule only works with numbers
I currently try to get the link
example.com/subdir/StackExchange/
to act as a link with e.g. an additional website tag:
example.com/subdir?website=StackExchange
I set up a RewriteRule in the .htaccess that looks as following:
RewriteRule ^subdir/(.*)/$ subdir.php?website=$1 [L]
When I use numbers (example.com/subdir/123/
), echo $_GET["website"]
successfully echoes "123". As soon as I use alphabetical letters (example.com/subdir/abc/
) it does not work.
How do I get this changed? Is this an issue with WordPress? I have set the permalink option in the WordPress Settings Dashboard to "Post name". I tried other methods, too, but nothing has changed.
Solution
Leave .htaccess
alone. You can use WordPress rewrite API for this.
add_action( 'init', function(){
return add_rewrite_rule(
'subdir/([^/]+)/?$', // ([^/]+) takes alphanumeric, while ([0-9]+) accepts digits
'index.php?pagename=subdir&website=$matches[1]',
'top'
);
});
add_filter('query_vars', function($v){ return array_merge(array('website'),$v); });
First make sure subdir
is a valid page slug, in this example. After you save that code to your child theme's functions file or plugin, you can now use get_query_var('website')
to get the website
property rather than using $_GET
global.
Hope that helps.