.htaccess redirect with exceptions

2019-08-12 07:34发布

问题:

I am trying to redirect all visits to a specific sub-folder with a few exceptions.

This is the URL I am trying to redirect:

  • www.example.com/my-sub-folder/

I would like any hits to anything under that URL to be redirected to the following URL:

  • www.example.com/news/category/my-new-sub-folder/

Except, I don't want to redirect these URLs:

  • www.example.com/my-sub-folder/my-special-folder/.*
  • www.example.com/my-sub-folder/wp-admin/.*

I have tried to do the following within my .htaccess file but it does not seem to deal with the exceptions:

RewriteCond %{REQUEST_URI} !^/my-sub-folder/my-special-folder(/.*)?$ [OR]
RewriteCond %{REQUEST_URI} !^/my-sub-folder/wp-admin(/.*)?$ 
RewriteCond %{REQUEST_URI} ^/my-sub-folder(/.*)?$ 
RewriteRule ^(.*)$ /news/category/my-new-sub-folder/ [R=301,L]

What am I doing wrong or is there a better way?

Thanks

回答1:

It's because you are using OR in the conditions you need to include all the conditions. Try this rule.

RewriteCond %{REQUEST_URI} !^/my-sub-folder/my-special-folder/? [NC]
RewriteCond %{REQUEST_URI} !^/my-sub-folder/wp-admin/? [NC]
RewriteCond %{REQUEST_URI} ^/my-sub-folder/?
RewriteRule ^(.*)$ /news/category/my-new-sub-folder/ [R=301,L]


回答2:

Well you tagged it Wordpress, so you could use the Wordpress rewrite API instead of manually adding htaccess rules. Here is the codex: http://codex.wordpress.org/Rewrite_API/add_rewrite_rule Then put the rules in a plugin or your theme's functions.php file.