Custom rewrite rule, url returning 404

I have a custom URL like this:

website.com/show/?id=9999n=page-name

and I'm trying to come up with a mod_rewrite rule to convert to

website.com/show/9999/page-name/

/show/ is a page name.

Here's the rules I'm using in .htaccess:

IfModule mod_rewrite.c
Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteRule ^show/(.*)$ /show/?id=$1 [R=301,NC,QSA]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
/IfModule

This is working, it rewrites

 website.com/show/?id=9999`

to

website.com/show/9999/

Then I modified the rule for the second query string:

RewriteRule ^show/(.*)/(.*)$ /show/?id=$1n=$2 [R=301,NC,QSA]

But website.com/show/9999/page-name/ returns a 404 error.
It works if I go to: website.com/show/9999/?n=page-name.

What am I doing wrong?

Topic mod-rewrite htaccess Wordpress

Category Web


I think I figured it out... almost. I needed to use WordPress' own rewrite engine to define the rewrite rules so it recognizes what I'm doing.

So I added this to my WordPress theme's functions.php:

add_action( 'init', 'init_custom_rewrite' );

function init_custom_rewrite() {
    add_rewrite_rule(        
        '^show/([^/]*)/([^/]*)/?',        
        'index.php?page_id=2382&id=$matches[1]&n=$matches[2]',        
        'top' );
}

add_filter('query_vars', 'my_query_vars', 10, 1);

function my_query_vars($vars) {
    $vars[] = 'id';
    $vars[] = 'n';
    return $vars;
}

The URL website.com/show/9999/page-name works correctly.

Now I need to redirect the old query string URL: website.com/show/?id=9999&n=page-name to the new SEO friendly url: website.com/show/9999/page-name

I do that with some rewrite rules in .htaccess:

RewriteCond %{QUERY_STRING} ^id=([^/]*)&n=([^/]*)$ 
RewriteRule ^showtest/?$ /showtest\/%1\/%2\/? [R=301,L]

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.