1

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.

1

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.

  • Hey Samuel, thanks for your answer. I tried to use your code, but I still receive 404s when using alphanumerics, while numbers are still working. I removed the rule from .htaccess, so that can't be the reason why it still occurs. It is also a valid page slug. These Rules are also within the .htaccess: RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L,NS] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L,NS] Is one of them blocking it? For me, it does not seem like it. Thanks in Advance! – H. Grimm Nov 27 '16 at 22:09
  • After adding the code, did you go to Settings > Permalinks and hit the saving button (to flush the rules)? Just restore your .htaccess with a fresh copy from WordPress – Samuel Elh Nov 27 '16 at 22:28
  • Flushing the rules did it finally! Thank you so much Samuel, you really ended my hours-long struggle! =) – H. Grimm Nov 27 '16 at 22:36
  • You're very welcome. Have a good day! – Samuel Elh Nov 27 '16 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.