Daan Twice
Daan Twice

Reputation: 337

Redirect folder only using htaccess, not pages in folder

I have a link structure dynamically generated based on this:

http://www.website.com/profiles/

This page shows a listing of all profiles.

For filtering reasons, we also have

http://www.website.com/profile-category/categoryA/

This would only list the profiles of category A. However, when one removes the '/categoryA/' from this url, they get a 404 page not found.

I would like to redirect http://www.website.com/profile-category/ without http://www.website.com/profile-category/categoryA/ being affected. Is this possible using .htaccess?

I know the directory redirect in .htaccess, but this also affects all underlying pages.

Existing rewrite rules:

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

  RewriteRule ^index\.php$ - [L]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Upvotes: 0

Views: 1676

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270795

To ensure nothing following the bare directory path is matched, terminate it with a $ and optionally allow a trailing slash with /?. Order is very important with rewrite rules, so you must place this before WordPress's final catch-all rule.

First, test placing it before any of WordPress' rules. Failing that, insert it between them.

RewriteEngine On
# Redirect profile-category with nothing following to /profiles list
RewriteRule ^profile-category/?$ /profiles [L,R=301]

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

  RewriteRule ^index\.php$ - [L]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.php [L]
</IfModule>
# END WordPress

I left WP's full block above because I'm not sure if it is dynamically written by the application (which could break your rule occasionally). A more logical arrangement for the entire set of rules would be:

RewriteEngine On
RewriteBase /

# Never modify requests to index.php
RewriteRule ^index\.php$ - [L]

# Redirect profile-category with nothing following to /profiles list
RewriteRule ^profile-category/?$ /profiles [L,R=301]

# Wordpress - write all requests to non-existing files & dirs
# into index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Upvotes: 2

Related Questions