Ron
Ron

Reputation: 33

Exclude a URL from folder redirection

I am redirecting all URLs from www.example.com/forums to www.example.com/blog/.

so I made this rule in .htaccess:

RewriteRule ^forums blog/$1 [L,R=301]

the thing is that I want to exclude some URLs that also begin with forums/ and redirect them to particular URL other than /blog.

For example, forums/8/some-made-up-word-here-1681 to /studies/some-made-up-studies.

Right now, it redirects to /blog like all URLs that start with forum/

Upvotes: 2

Views: 54

Answers (1)

MrWhite
MrWhite

Reputation: 45829

You just need to include the more specific redirects first, before the more general rule. For example:

RewriteEngine On

# Specific redirects
RewriteRule ^forums/8/some-made-up-word-here-1681 /studies/some-made-up-studies [R,L]

# Redirect all other URLs that start /forums
RewriteRule ^forums/?(.*) /blog/$1 [R,L]

I've also modified your existing directive to redirect /forums/<something> to /blog/<something>, which I assume was perhaps the original intention, since you were using a $1 backreference in the substitution, but did not have a capturing group in the RewriteRule pattern. Your original directive would have redirected /forums/<something> to /blog/.

I've also included a slash prefix on the substitution. This is required for redirects, although you may have set RewriteBase instead, in which case you do not need to do this.

You will need to clear your browser cache before testing, since the earlier catch-all 301 will have been cached hard by the browser. For this reason it is often easier to test with temporary 302s in order to avoid the caching problem. Change the above temporary redirects to 301s only after you have confirmed this is working as intended.

UPDATE: To redirect all URLs that start /forums to /blog/, without copying the remainder of the URL, then change the last directive to read:

# Redirect all other URLs that start /forums
RewriteRule ^forums /blog/ [R,L]

Basically, the $1 in your original directive was superfluous.

Upvotes: 1

Related Questions