Reputation: 6449
I want to add a rule to my .htaccess file that doesn't follow the Wordpress default rules.
Everything like this:
1- /course/(:any)
Must be redirected to this:
2- /course/?slug=$1
But I want to keep the URL in 1, without the query string.
Everything I try either gives me an internal server error or doesn't match the rule. This is what I got and is just being ignored (because the wordpress shows me a 'page not found' message). The resulting URL is like http://localhost/bethmoda/courses/?slug
without the parameter and changing the URL
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)/course/(.*)$ /bethmoda/course?slug=$2 [L]
RewriteBase /bethmoda/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /bethmoda/index.php [L]
</IfModule>
# END WordPress
How can I do this?
Upvotes: 2
Views: 1028
Reputation: 919
The following is a wordpress way to achieve what you want.
If possbile: change "slug" with something else, lets say "course-slug".
//Add query variable, so that wordpress identifies your custom query string
function add_custom_query_var( $qvars ) {
$qvars[] = 'course-slug';
return $qvars;
}
add_filter('query_vars', 'add_custom_query_var');
Add your custom rewrite rules
//Assumption: course is a page
add_filter( 'rewrite_rules_array', 'custom_rewrite_rules' );
function custom_rewrite_rules( $rewrite_rules )
{
$pattern = "course/([^/]+)?$";
$target = "index.php?" . "name=course&course-slug=\$matches[1]";
// If course was a custom post type
// $target = "index.php?" . "post_type=course&course-slug=\$matches[1]";
// If course was a category
// $target = "index.php?" . "category_name=course&course-slug=\$matches[1]";
// If course was a tag
// $target = "index.php?" . "tag=course&course-slug=\$matches[1]";
$newRules[$pattern] = $target;
return array_merge($newRules,$rewrite_rules);
}
Flush permalink
Step 1: In the main menu find "Settings > Permalinks".
Step 2: Scroll down if needed and click "Save Changes".
Step 3: Rewrite rules and permalinks are flushed.
Upvotes: 0
Reputation: 41249
You can use the following rule :
RewriteEngine On
#Exclude /bethmoda/course/index.php
RewriteCond %{REQUEST_URI} !^/bethmoda/course/index\.php$
RewriteRule ^/?bethmoda/course/(.+)$ /bethmoda/course/?slug=$1 [NC,L]
The rewriteCond is important to avoid RewriteLoop error on the second rewrite iteration, otherwise without this condition You will get an Internal server error.
Upvotes: 1