I'm migrating a site between hosts and am having issues with what should be(!) a fairly simple rewrite of a "pretty" URL to display posts filtered by category.

domain.xyz/category/cat_name/ => domain.xyz/blog/?wpc_term=cat_name

Using .htaccess, the following rule works:

# Works, but redirects the browser
RewriteRule ^category/([^/]+)/?$ blog/?wpc_term=$1 [L,R=301]

However, the client wants the URL to remain the same in the browser - the URL should be rewritten, not redirected - but removing the redirect flag [R=301] results in a 404 page

# Doesn't work -> 404 page
RewriteRule ^category/([^/]+)/?$ blog/?wpc_term=$1 [L]

I've also tried the following in the theme's functions.php - this also 404s.

add_action('init', function() {
  add_rewrite_rule( '^category/([^/]+)/?', 'blog/?wpc_term=$matches[1]', 'top' );

The old server was a shared hosting provider with its own admin panel for adding redirects, so I've no idea how they implemented on that server - however, it all works fine there so it must be possible!

EDIT to add full .htaccess file:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# Works, but redirects browser :(
RewriteRule ^category/([^/]+)/?$ blog/?wpc_term=$1 [L,R=301]

# Standard WP .htaccess follows...
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress

WP is installed in webroot directory, not a subdirectory.

No other .htaccess files in subdirectories.

  • 1
    Can you add your entire .htaccess file to your question, thanks. Is WordPress installed in the /blog subdirectory? Which .htaccess file are you editing? Do you have additional .htaccess files in subdirectories? – MrWhite Sep 7 '18 at 14:57
  • @MrWhite I've edited the question to include the information you asked for - thanks – Andy P Sep 7 '18 at 16:03
  • I'm assuming blog isn't a physical directory, so it makes sense why that would 404 with a Last rule flag. The default WordPress rule forwards everything to index.php, which is ultimately where those requests need to be routed. – Milo Sep 7 '18 at 16:31
  • @Milo that does happen if I use the [END] flag instead, resulting in a "hard" 404 - whereas with [L] the rewritten URL does get parsed by WP and results in a "soft" 404 page (perhaps because there are no posts with /category/cat_name/ as the slug?) – Andy P Sep 7 '18 at 16:59
  • 1
    "because there are no posts with /category/cat_name/ as the slug?" - Yes, that is most probably the issue. WordPress routes the request based on the requested URL (the URL you see in the browsers address bar), not the URL you are rewriting to. – MrWhite Sep 7 '18 at 17:51

Your Answer

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

Browse other questions tagged or ask your own question.